//#define DISABLE_ARGLIST

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using System.Diagnostics;
using Meta;

namespace Meta.Editor {
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Editor : System.Windows.Forms.Form {
		public static CodeBox.Style defaultNormalStyle = new CodeBox.Style(new Font("Arial", 11.0F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point,	((System.Byte)(0))), Color.Black);
		public static CodeBox.Style defaultTitleStyle = new CodeBox.Style(new Font("Arial", 13.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point,	((System.Byte)(0))), Color.Black);
		public static CodeBox.Style defaultCommentStyle = new CodeBox.Style(new Font("Arial", 11.0F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point,	((System.Byte)(0))), Color.Black);
		public static readonly System.Drawing.Icon DefaultIcon = ((System.Drawing.Icon)(new System.Resources.ResourceManager(typeof(Editor)).GetObject("$this.Icon")));
		public static Color defaultBackgroundColor = Color.LightGray;
		//public static bool indentDefsLispStyle = false;
		public static bool fastMode=false;
		public static bool insertMatchingBrackets=false;
		public static bool BlankLinesMarkTopLevelRegions = false;
		public static bool OnlyTopLevelDefs = false;

		private System.Windows.Forms.Timer arglistTimer;
		public static int arglistPeriod = 3000;
		private string arglistOperator;
		public FileToken fileToken;
		// Need to maintain our own modified flag  because code.Modified gets set for
		// events that don't actually change the file text.
		bool reallyModified = false;

		private System.Windows.Forms.ToolStripMenuItem formatBullet;
		private System.Windows.Forms.ToolStripMenuItem speedUpEditorMenuItem;
		private System.Windows.Forms.ToolStripMenuItem InterruptExecution;
		private System.Windows.Forms.ToolStripMenuItem fontMenuItem;
		private System.Windows.Forms.ToolStripMenuItem examplesMenuItem;
		private System.Windows.Forms.ToolStripMenuItem advancedMenu;
		private System.Windows.Forms.ToolStripMenuItem backgroundColorMenuItem;
		private static ColorDialog colorDialog = new ColorDialog();
		private System.Windows.Forms.ToolStripMenuItem forceGCMenuItem;
		private System.Windows.Forms.ToolStripMenuItem editorSubmenu;
		private System.Windows.Forms.ToolStripMenuItem debugSubmenu;
		private System.Windows.Forms.ToolStripMenuItem wizardSubmenu;
		private System.Windows.Forms.ToolStripMenuItem loadMenuItem;
		private System.Windows.Forms.ToolStripMenuItem pasteCommandMenuItem;
		private System.Windows.Forms.ToolStripMenuItem pasteNextCommandMenuItem;
		private System.Windows.Forms.ToolStripMenuItem undoMenuItem;
		private System.Windows.Forms.ToolStripMenuItem NormalStyleMenuItem;
		private System.Windows.Forms.ToolStripMenuItem TitleStyleMenuItem;
		private System.Windows.Forms.ToolStripMenuItem CommentStyleMenuItem;
		private System.Windows.Forms.ToolStripMenuItem styleMenu;
		private System.Windows.Forms.ToolStripMenuItem editStylesMenuItem;
		private System.Windows.Forms.ToolStripMenuItem setDefaultMenuItem;
		private System.Windows.Forms.ToolStripMenuItem executeSelectionMenuItem;
        private System.Windows.Forms.ToolStripMenuItem searchMenuItem;
		private System.Windows.Forms.ToolStripMenuItem contextCut;
		private System.Windows.Forms.ToolStripMenuItem contextCopy;
        private System.Windows.Forms.ToolStripMenuItem contextPaste;
		private System.Windows.Forms.ToolStripMenuItem contextExecute;
		private System.Windows.Forms.ToolStripMenuItem contextSingleStep;
        private System.Windows.Forms.ToolStripMenuItem contextInspect;
		private System.Windows.Forms.ToolStripMenuItem contextFindDefinition;
        private System.Windows.Forms.ToolStripMenuItem contextBreakpoint;
		private System.Windows.Forms.ToolStripMenuItem findMenuItem;
		private System.Windows.Forms.ToolStripMenuItem tailRecursionMenu;
		private System.Windows.Forms.ToolStripMenuItem fullTailRecursionMenuItem;
		private System.Windows.Forms.ToolStripMenuItem selfTailRecursionMenuItem;
		private System.Windows.Forms.ToolStripMenuItem noTailRecursionMenuItem;
		private System.Windows.Forms.ToolStripMenuItem reindentMenuItem;
        private System.Windows.Forms.ToolStripMenuItem reindentAllMenuItem;
		private System.Windows.Forms.ToolStripMenuItem restyleMenuItem;
		private System.Windows.Forms.ToolStripMenuItem restyleAllMenuItem;
		private System.Windows.Forms.ToolStripMenuItem restyleAllPreservingCommentsMenuItem;
		private System.Windows.Forms.ToolStripMenuItem clearAllBreakpointsMenuItem;
        private System.Windows.Forms.ToolStripMenuItem breakpointExpressionMenuItem;
		private System.Windows.Forms.ToolStripMenuItem continueExecutionMenuItem;
		private System.Windows.Forms.ToolStripMenuItem beginnerModeMenuItem;
		private System.Windows.Forms.ToolStripMenuItem contextBreakpointExpressionMenuItem;
		private System.Windows.Forms.ToolStripMenuItem contextContinueExecutionMenuItem;
        private System.Windows.Forms.ToolStripMenuItem windowsMenu;
		private System.Windows.Forms.ToolStripMenuItem traceMenuItem;
		private System.Windows.Forms.ToolStripMenuItem clearAllTracesMenuItem;
        private System.Windows.Forms.ToolStripMenuItem contextTrace;
		private System.Windows.Forms.ToolStripMenuItem traceLoadMenuItem;
		private System.Windows.Forms.ToolStripMenuItem zoomMenu;
		private System.Windows.Forms.ToolStripMenuItem zoom120;
		private System.Windows.Forms.ToolStripMenuItem zoom110;
		private System.Windows.Forms.ToolStripMenuItem zoom100;
		private System.Windows.Forms.ToolStripMenuItem zoom90;
		private System.Windows.Forms.ToolStripMenuItem zoom80;
		private System.Windows.Forms.ToolStripMenuItem zoom150;
		private System.Windows.Forms.ToolStripMenuItem zoom200;
		private System.Windows.Forms.ToolStripMenuItem zoom300;
		private System.Windows.Forms.ToolStripMenuItem ShowReferencesMenuItem;
		private System.Windows.Forms.ToolStripMenuItem ShowReferencesMenuItem2;
		private System.Windows.Forms.ToolStripMenuItem ISearchMenuItem;
		private System.Windows.Forms.ToolStripMenuItem fKeyMenuItem;
        private System.Windows.Forms.ToolStripMenuItem findUnbalancedMenuItem;
		private System.Windows.Forms.ToolStripMenuItem ReplaceMenuItem;
		private System.Windows.Forms.ToolStripMenuItem RemoveWhitespaceMenuItem;
		private System.Windows.Forms.ToolStripMenuItem CheckMenu;
		private System.Windows.Forms.ToolStripMenuItem CheckMenuItem;
        private System.Windows.Forms.ToolStripMenuItem AutoCheckMenuItem;
		protected System.Windows.Forms.ToolStripMenuItem GotoMenuItem;
		private System.Windows.Forms.ToolStripMenuItem RecenterMenuItem;
		private System.Windows.Forms.ContextMenuStrip contextMenu;
        private System.Windows.Forms.ToolStripMenuItem traceAnalysisMenuItem;
		private System.Windows.Forms.ToolStripMenuItem contextFindUsesMenuItem;
        private ToolStripSeparator editSeparator2;
        private ToolStripSeparator editSeparator3;
        private ToolStripSeparator menuItem5;
        private ToolStripSeparator fileSeparator1;
        private ToolStripSeparator fileSeparator2;
        private ToolStripSeparator fileSeparator3;
        private ToolStripSeparator editSeparator1;
        private ToolStripSeparator editSeparator4;
        private ToolStripSeparator menuItem6;
        private ToolStripSeparator formatSeparator1;
        private ToolStripSeparator formatSeparator2;
        private ToolStripSeparator formatSeparator3;
        private ToolStripSeparator formatSeparator4;
        private ToolStripSeparator styleSeparator1;
        private ToolStripSeparator menuItem2;
        private ToolStripSeparator executeSeparator1;
        private ToolStripSeparator executeSeparator2;
        private ToolStripSeparator menuItem3;
        private ToolStripSeparator menuItem1;
        private ToolStripSeparator menuItem4;
        private ToolStripSeparator helpSeparator1;
        private ToolStripSeparator contextSeparator1;
        private ToolStripSeparator contextSeparator2;
        private ToolStripSeparator menuItem7;
        private ToolStripSeparator contextSeparator3;

		///
		/// Stuff for keeping track of the set of editor windows
		///
		private static Hashtable editorTable = new Hashtable();
		public static Editor FindEditor(FileToken fullPathName) {
			return FindEditor(fullPathName, true);
		}
		public static Editor FindEditor(FileToken fullPathName, bool create) {
			object probe = editorTable[fullPathName];

			if (probe is Editor)
				return (Editor)probe;
			else if (create && fullPathName.Path!=null) {
				Editor e = new Editor(fullPathName);
				e.Show();

				return e;
			} else
				return null;
		}

		///
		/// Namespace<->buffer tracking
		///
		static Hashtable fileNamespaceTable = new Hashtable();
		// Called when the user does [namespace <foo>]
		static void NotePackage() {
			FileToken file = Meta.TopLevel.CurrentSourceFileToken;

			if (file==null)
				return;

			// Remember the new namespace for this file.
			fileNamespaceTable[file] = Namespace.CurrentNamespace;
			Editor e = FindEditor(file, false);
			if (e!=null)
				e.ShowNamespace();

			// Kluge - we want a namespace command executed in the main listener to change the global default namespace
			if (e == Listener.mainListener)
				Meta.Namespace.currentNamespaceFluid.DefaultValue = Namespace.CurrentNamespace;
		}
		public static Namespace FileNamespace(FileToken token) {
			object probe = fileNamespaceTable[token];;
			if (probe!=null)
				return (Namespace)probe;
			else
				return PackageDirectory.Find(token.Path);
		}

		private void RemoveFromEditorTable() {
			lock (editorTable) {
				editorTable[fileToken] = null;
			}
		}
		private void AddToEditorTable() {
			lock (editorTable) {
				editorTable[fileToken] = this;
			}
		}

		public static void SetAllCursorsInternal(Cursor newCursor) {
			lock (editorTable) {
				foreach (DictionaryEntry window in editorTable) {
					Editor w = window.Value as Editor;

					if (w != null)
                        w.code.Cursor = newCursor;
				}
			}
		}

		public static bool CloseAllEditorWindows() {
			ArrayList allWindows = new ArrayList();
			// This is subtle;  We can't close the windows
			// inside the enumeration of the editorTable
			// because closing mutates the editorTable.
			lock (editorTable) {
				foreach (DictionaryEntry window in editorTable) {
					Editor w = window.Value as Editor;

					if (w != null && !(w is Listener)) 
						allWindows.Add(w);
				}
			}
			foreach (Editor e in allWindows) {
				e.Close();
				if (e.Controls.Count>0)
					return true;
			}
			return false;
		}

		protected static void DumpEditors(IDictionary dump) {
			ArrayList allWindows = new ArrayList();
			lock (editorTable) {
				foreach (DictionaryEntry window in editorTable) {
					Editor w = window.Value as Editor;

					if (w != null && w.code.Rtf.Length<50000) 
						allWindows.Add(new EditorState(w.Name, w.code.Rtf));
				}
			}
			dump.Add("Editor windows", allWindows);
		}

		[Serializable]
		protected class EditorState : IObjectReference {
			string name;
			string contents;

			public EditorState(string name, string contents) {
				this.name = name;
				this.contents = contents;
			}

			object IObjectReference.GetRealObject(StreamingContext ignore) {
				Editor ed = new Editor("Dump of "+((name==null)?"unnamed":name), contents);
				ed.Show();
				return ed;
			}
		}

		private System.Windows.Forms.ToolStripMenuItem formatBold;
		private System.Windows.Forms.ToolStripMenuItem formatItalic;
		private System.Windows.Forms.ToolStripMenuItem formatSuperscript;
		private System.Windows.Forms.ToolStripMenuItem formatSubscript;
		private System.Windows.Forms.ToolStripMenuItem formatGrow;
		private System.Windows.Forms.ToolStripMenuItem formatShrink;
		private System.Windows.Forms.ToolStripMenuItem formatMenu;
		private System.Windows.Forms.ToolStripMenuItem lowLevelDebugMenuItem;
		private System.Windows.Forms.ToolStripMenuItem showDetailMenuItem;
	
		delegate void StupidDelegateDecl(Cursor x);
		private static StupidDelegateDecl setCursorDelegate = new StupidDelegateDecl(SetAllCursorsInternal);

		public void SetAllCursors(Cursor newCursor) {
			Invoke(setCursorDelegate, new object[1] {newCursor});
		}

		static Expression TopLevelExpression(Expression e) {
			if (e.enclosingExpression==null)
				return e;
			else
				return TopLevelExpression(e.enclosingExpression);
		}

		static int SourceOffset(Expression e) {
			if (e.sourceLocation<0)
				return 0;
			Expression top = TopLevelExpression(e);
			if (top.sourceLocation<0)
				return 0;
			else
				return e.sourceLocation-top.sourceLocation;
		}

		delegate void StupidDelegateType(Meta.Expression e, bool loc, bool raise);

		// This is the version to be called from Meta code
		public static void EditSource(Meta.Expression e) {
			Listener.mainListener.Invoke(new StupidDelegateType(EditSource), new object[] { e, true, true });
		}

		// Should not be called from Meta code
		protected static void EditSource(Meta.Expression e, bool localizeToExpression, bool raise) {
			if (e==null)
				return;

			if (e.sourceFile!=null) {
				Editor p = FindEditor(e.sourceFile);
				if (p!=null) {
					p.code.LockWindow();
					// e.definedIn gets set to null for a globalvariablereference that's the operator in an application, at least in a method
					// find out why.
					if (e.definedIn==null && e.enclosingExpression!=null && e.enclosingExpression.definedIn!=null)
						e = e.enclosingExpression;
					if (e.definedIn==null) {
						if (e.sourceLocation>=0) {
							p.code.UserSelection = new Region(e.sourceLocation, 0);
							p.code.RestoreUserSelection();
							p.code.HideSelection = false;
							if (raise)
								p.BringToFront();
							p.code.ScrollToCaret();
							System.Windows.Forms.Application.DoEvents();  // Force it to scroll to the beginning before highlighting.
							p.code.MaybeHighlightAfter();
						} 
#if INFORMNOSOURCEFILE
						else
							MessageBox.Show("Sorry, I can't find the location of that expression in the source file.", "Can't find source code", MessageBoxButtons.OK);
#endif
					} else {
						// Yuk!
						string headerPattern = Regex.Escape(e.definedIn);
						if (e.definedIn.StartsWith("["))
							// It's a method description; hack it to be tolerant of extra whitespace
							headerPattern = headerPattern.Replace("\\ ","\\s+");
						else
							// It's a variable name; hack it to prevent it from matching the interiors of words
							//headerPattern = headerPattern+"[ $\r\n)\\]]";
							headerPattern = headerPattern+"[\\s\\]]";
						String searchPattern = "[[(]define[^[( ]* +[[(]*"+headerPattern;
						System.Text.RegularExpressions.Regex r = new Regex(searchPattern);
						string text = p.code.Text;
						Match m = r.Match(text);
						//int start = text.IndexOf("[define "+e.definedIn);
						//if (start>=0) {
						if (m.Success) {
							int start = m.Index;
							p.code.ScrollToPosition(start);
							if (localizeToExpression) {
                                Region ur = p.code.UserSelection;
								ur.start += SourceOffset(e);
                                p.code.UserSelection = ur;
								p.code.RestoreUserSelection();
								System.Windows.Forms.Application.DoEvents();  // Force it to scroll to the beginning before highlighting
								p.code.MaybeHighlightAfter();
							} else {
								int offset = SourceOffset(e);
								p.code.UserSelection = new Region((offset>0)?offset:start, 0);
								p.code.RestoreUserSelection();
							}
							p.code.HideSelection = false;
							p.code.ScrollToCaret();
							if (raise)
								p.BringToFront();
						} else
							MessageBox.Show("Sorry, I can't find the location of that expression in the source file.  I'm using the last known location of the expression.", "Can't find source code", MessageBoxButtons.OK);
					}
					p.SnapToDebugger();
					p.code.ScrollToTop();
					p.code.UnlockWindowDammit();
				}
			} else
				MessageBox.Show("Sorry, I can't determine what file the code came from.", "Can't find source code", MessageBoxButtons.OK);
			SetAllCursorsInternal(Cursors.Default);
		}

		public void SnapToDebugger() {
			int screenEnd = Screen.PrimaryScreen.Bounds.Right;
			Inspector d = Meta.TopLevel.CurrentDebugger;
			if (d!=null  && !d.IsDisposed && d.Visible) {  // paranoid
				d.Top = this.Top;

				int w = d.Width;
				if (Left>(w+1))
					d.Left = this.Left-(w+1);
				else if ((this.Right+w+1) < screenEnd)
					d.Left = this.Right+1;
				// else can't do anything because the debugger won't fit
					
				d.BringToFront();
				//this.BringToFront();
			}
		}

		public string saveFileName = null;
        private StringReader myReader;
        private IContainer components;
		private System.Windows.Forms.ToolStripMenuItem File;
		private System.Windows.Forms.ToolStripMenuItem Execute;
		private System.Windows.Forms.ToolStripMenuItem Edit;
		private System.Windows.Forms.ToolStripMenuItem Cut;
		private System.Windows.Forms.ToolStripMenuItem Copy;
		private System.Windows.Forms.ToolStripMenuItem Paste;
		private System.Windows.Forms.ToolStripMenuItem Evaluate;
		private System.Windows.Forms.ToolStripMenuItem StopExec;
		private System.Windows.Forms.ToolStripMenuItem FileNew;
		private System.Windows.Forms.ToolStripMenuItem FileOpen;
		private System.Windows.Forms.ToolStripMenuItem FileClose;
		private System.Windows.Forms.ToolStripMenuItem FileSave;
		private System.Windows.Forms.ToolStripMenuItem FileSaveAs;
		private System.Windows.Forms.ToolStripMenuItem FileExit;
		private System.Windows.Forms.ToolStripMenuItem HelpMenu;
		private System.Windows.Forms.ToolStripMenuItem FilePrint;
		private System.Windows.Forms.ToolStripMenuItem PreviewMenu;
		private System.Windows.Forms.ToolStripMenuItem PrinterSettingsMenu;
		private System.Windows.Forms.PrintDialog printDialog1;
		private System.Drawing.Printing.PrintDocument ThePrintDocument;
		private System.Windows.Forms.StatusBar statusBar;
		private System.Windows.Forms.MenuStrip mainMenu;
		private System.Windows.Forms.ToolStripMenuItem SingleStepMenuItem;
		private System.Windows.Forms.ToolStripMenuItem inspectMenuItem;
		private System.Windows.Forms.StatusBarPanel valuePanel;
		private System.Windows.Forms.StatusBarPanel arglistPanel;
		private System.Windows.Forms.ToolStripMenuItem executeAllMenuItem;
		private System.Windows.Forms.ToolStripMenuItem SelectAll;
		private System.Windows.Forms.ToolStripMenuItem FindDefinitionMenuItem;
		private System.Windows.Forms.ToolStripMenuItem transposeMenuItem;
		protected CodeBox code;
		private System.Windows.Forms.ToolStripMenuItem breakpointMenuItem;

		private void EditorInit() {
			if (!DesignMode) {
				this.ThePrintDocument = new System.Drawing.Printing.PrintDocument();
#if SYNTAXHIGHLIGHTING
				HighLightMenu.Checked = EditorConfiguration.doHighlight;
#endif
				Controls.Add(code);
                Rectangle max = MaximizedBounds;
                max.X = Left;
                max.Width = Width;
                max.Height = Screen.FromControl(this).WorkingArea.Height;
                MaximizedBounds = max;
				code.ContextMenuStrip = contextMenu;
				arglistTimer = new System.Windows.Forms.Timer();
				arglistTimer.Stop();
				arglistTimer.Tick += new EventHandler(ShowDocumentation);
				arglistTimer.Interval = arglistPeriod;
				SetArglistText("");
				code.MarkUndo();
				//code.SpacePressed += new Thunk(MaybeShowArglist);
#if !DISABLE_ARGLIST
				code.SelectionChanged += new EventHandler(MaybeShowArglist);
#endif
				code.VerticalPositionChanged += new Thunk(UpdateVariableValue);
				//code.ModifiedChanged += new EventHandler(HandleModified);
				code.TextChanged += new EventHandler(HandleModified);
				Closing += new CancelEventHandler(HandleClose);
				System.Windows.Forms.Application.ApplicationExit += new EventHandler(HandleQuit);
				//HelpMenu.MenuItems.Add(new CodeFileMenuItem("Release notes for this version", Meta.Installation.HelpFilePath("Release notes.meta")));
				HelpMenu.DropDownItems.Insert(0, new HelpDirectoryMenuItem("Packages", Meta.Installation.installDirectory+"\\Packages"));
				HelpMenu.DropDownItems.Add(new Meta.HelpMenuItem("Programming environment",
					Meta.Installation.HelpFilePath("Programming environment.htm"),
					Keys.F1));
				HelpMenu.DropDownItems.Add(new Meta.HelpMenuItem("Language reference manual", Meta.Installation.HelpFilePath("Meta language.htm")));
				HelpMenu.DropDownItems.Add(new Meta.HelpMenuItem("Introduction for Scheme programmers", Meta.Installation.HelpFilePath("Meta for Scheme programmers.htm")));
				HelpMenu.DropDownItems.Add(new Meta.HelpMenuItem("Release notes", Meta.Installation.HelpFilePath("Release notes.htm")));
				HelpMenu.DropDownItems.Add(new Meta.HelpMenuItem("Implementation notes", Meta.Installation.HelpFilePath("Implementation notes.htm")));
				
				new StaticFlagMenuItem(editorSubmenu, "Switch to interaction window on eval", "Listener", "focusOnWrite");
				new StaticFlagMenuItem(editorSubmenu, "Insert matching brackets", "Editor", "insertMatchingBrackets");
				//new StaticFlagMenuItem(editorSubmenu, "Indent definitions LISP style", "Editor", "indentDefsLispStyle");
				new StaticFlagMenuItem(debugSubmenu, "Show &All expressions in debugger", "EvalStack", "showAllExpressions");
				new StaticFlagMenuItem(advancedMenu, "Always use Basic2D graphics package", "TopLevel", "AlwaysOpen2D");
				//code.BackColor = defaultBackgroundColor;
				ShowNamespace();
				fKeyMenuItem.DropDownItems.AddRange(new ToolStripMenuItem[] {
																   // new FKeyMenuItem(Shortcut.F1),   // don't want to shadow the help key
																   new FKeyMenuItem(Keys.F2),
																   new FKeyMenuItem(Keys.F3),
																   new FKeyMenuItem(Keys.F4),
																   new FKeyMenuItem(Keys.F5),
																   new FKeyMenuItem(Keys.F6),
																   new FKeyMenuItem(Keys.F7),
																   new FKeyMenuItem(Keys.F8),
																   new FKeyMenuItem(Keys.F9),
																   new FKeyMenuItem(Keys.F10),
																   new FKeyMenuItem(Keys.F11),
																   new FKeyMenuItem(Keys.F12)
															   });
				FKeyMenuItem_Popup(null, null);
				AddToEditorTable();
			}
		}

		static Editor() {
			Meta.Namespace.CurrentNamespaceChanged += new VoidThunk(NotePackage);
			Meta.TopLevel.idle += new VoidThunk(UpdateFKeyMenus);
			Meta.TopLevel.WarningsChanged += new Meta.TopLevel.WarningHandler(UpdateAllCheckMenus);
			Meta.EvalStack.Dump += new Meta.EvalStack.DumpHandler(DumpEditors);
		}

        static void UpdateFKeyMenus()
        {
            Listener.mainListener.Invoke(new Meta.VoidThunk(ReallyUpdateFKeyMenus), new object[0]);
        }
		static void ReallyUpdateFKeyMenus() {
			foreach (DictionaryEntry entry in editorTable) {
				if (entry.Value != null)
					((Editor)entry.Value).FKeyMenuItem_Popup(null, null);
			}
		}

		public Editor() {
			code = new CodeBox();
			fileToken = new FileToken();
			InitializeComponent();
			EditorInit();
			code.BackColor = defaultBackgroundColor;
			code.SetRegionStyle(new Region(0, code.TextLength), code.TheStyle("Normal"));
			Text = Name ="Untitled";
			UpdateCheckMenuStatus();
		}

		public Editor(string name, string contents) : this() {
			this.Name = name;
			this.code.Rtf = contents;
			ClearModified();
		}

		public Editor(string fullPathName) : this(FileToken.GetToken(fullPathName)) {
		}

		public Editor(FileToken fileToken) {
			this.fileToken = fileToken;
			string fileName = fileToken.Path;

			code = new CodeBox();
			InitializeComponent();
			if (System.IO.File.Exists(fileName)) {
				FileName = fileName;
				try {
					if (Path.GetExtension(fileName)==".scm") {
						MessageBox.Show("File will be converted to .meta format", "Open scheme file");
						code.LoadFile(fileName, RichTextBoxStreamType.PlainText);
						saveFileName = FileName = Path.ChangeExtension(fileName, ".meta");
					} else {
						// Kluge - turn off undo for really big files.
						System.IO.FileStream f  = System.IO.File.Open(fileName,System.IO.FileMode.Open,System.IO.FileAccess.Read);
						if (f.Length>50000)
							code.undoEnabled = false;

						// Check for header
						string header = "{\\*\\metaConfig";
						byte[] headerBuffer = new Byte[header.Length];
						char[] usableHeader = new Char[header.Length];
						f.Read(headerBuffer, 0, headerBuffer.Length);
						headerBuffer.CopyTo(usableHeader,0);
						bool hasConfigInfo = new String(usableHeader)==header;
						if (hasConfigInfo) {
							StreamReader reader = new StreamReader(f);
							object[] configInfo = (object[])(new Reader(reader, 0).Read());
							foreach (object[] config in configInfo) {
								object head = config[0];
								if (head==Symbol.Intern("styles")) {
									for (int style=1; style<config.Length; style++)
										code.RegisterStyle("foo", null); // config[style]);
								} // else unrecognized configuration parameter - ignore.
							}
							reader.Close();
						}
						f.Close();
						//code.LoadFile(f, RichTextBoxStreamType.RichText);
						code.LoadFile(saveFileName, RichTextBoxStreamType.RichText);
					}
				} catch (Exception e) {
					MessageBox.Show("An exception ocurred while trying to read the file.  Are you sure it's a Meta file?", "Error opening file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					Meta.Inspector.Inspect(e);
				}
			} else {
				MessageBox.Show("Couldn't find the file "+fileName, "Error opening file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				Text = Name ="Untitled";
			}
			ClearModified();
			code.reIndent = false;
			EditorInit();
		}

		public string FileName {
			get {
				return saveFileName;
			}
			set {
				RemoveFromEditorTable();
				//Name = Path.GetFileName(value);
				Text = Name = Path.GetFileName(value);
				string path = Path.GetFullPath(value);
				saveFileName = path;
				fileToken.Path = path;
				AddToEditorTable();
			}
		}

		public Namespace Namespace {
			get {
				Namespace ns = FileNamespace(fileToken);
				return ns==null?Namespace.CurrentNamespace:ns;
			}
		}

		public void ShowNamespace() {
			SetValueText("Namespace: "+this.Namespace.ToString());
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing ) {
			System.Windows.Forms.Application.ApplicationExit -= new EventHandler(HandleQuit);
			// At one point, this seemed necessary to keep it from throwing an exception when closing an editor window.
			// code.Clear();
			if( disposing ) {
				if (components != null) {
					components.Dispose();
				}
			}
			RemoveFromEditorTable();
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Editor));
            this.mainMenu = new System.Windows.Forms.MenuStrip();
            this.File = new System.Windows.Forms.ToolStripMenuItem();
            this.FileNew = new System.Windows.Forms.ToolStripMenuItem();
            this.FileOpen = new System.Windows.Forms.ToolStripMenuItem();
            this.FileClose = new System.Windows.Forms.ToolStripMenuItem();
            this.fileSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.FileSave = new System.Windows.Forms.ToolStripMenuItem();
            this.FileSaveAs = new System.Windows.Forms.ToolStripMenuItem();
            this.setDefaultMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.fileSeparator2 = new System.Windows.Forms.ToolStripSeparator();
            this.FilePrint = new System.Windows.Forms.ToolStripMenuItem();
            this.PreviewMenu = new System.Windows.Forms.ToolStripMenuItem();
            this.PrinterSettingsMenu = new System.Windows.Forms.ToolStripMenuItem();
            this.fileSeparator3 = new System.Windows.Forms.ToolStripSeparator();
            this.FileExit = new System.Windows.Forms.ToolStripMenuItem();
            this.Edit = new System.Windows.Forms.ToolStripMenuItem();
            this.undoMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.editSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.Cut = new System.Windows.Forms.ToolStripMenuItem();
            this.Copy = new System.Windows.Forms.ToolStripMenuItem();
            this.Paste = new System.Windows.Forms.ToolStripMenuItem();
            this.SelectAll = new System.Windows.Forms.ToolStripMenuItem();
            this.editSeparator2 = new System.Windows.Forms.ToolStripSeparator();
            this.transposeMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.editSeparator3 = new System.Windows.Forms.ToolStripSeparator();
            this.pasteCommandMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.pasteNextCommandMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItem5 = new System.Windows.Forms.ToolStripSeparator();
            this.findUnbalancedMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.editSeparator4 = new System.Windows.Forms.ToolStripSeparator();
            this.ISearchMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.findMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.ReplaceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItem6 = new System.Windows.Forms.ToolStripSeparator();
            this.FindDefinitionMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.ShowReferencesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.ShowReferencesMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
            this.formatMenu = new System.Windows.Forms.ToolStripMenuItem();
            this.fontMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.formatSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.formatBold = new System.Windows.Forms.ToolStripMenuItem();
            this.formatItalic = new System.Windows.Forms.ToolStripMenuItem();
            this.formatBullet = new System.Windows.Forms.ToolStripMenuItem();
            this.formatSeparator2 = new System.Windows.Forms.ToolStripSeparator();
            this.formatGrow = new System.Windows.Forms.ToolStripMenuItem();
            this.formatShrink = new System.Windows.Forms.ToolStripMenuItem();
            this.formatSeparator3 = new System.Windows.Forms.ToolStripSeparator();
            this.formatSubscript = new System.Windows.Forms.ToolStripMenuItem();
            this.formatSuperscript = new System.Windows.Forms.ToolStripMenuItem();
            this.formatSeparator4 = new System.Windows.Forms.ToolStripSeparator();
            this.backgroundColorMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.reindentMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.reindentAllMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.RemoveWhitespaceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.styleMenu = new System.Windows.Forms.ToolStripMenuItem();
            this.editStylesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.styleSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.NormalStyleMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.TitleStyleMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.CommentStyleMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItem2 = new System.Windows.Forms.ToolStripSeparator();
            this.restyleMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.restyleAllMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.restyleAllPreservingCommentsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.Execute = new System.Windows.Forms.ToolStripMenuItem();
            this.Evaluate = new System.Windows.Forms.ToolStripMenuItem();
            this.inspectMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.executeSelectionMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.executeAllMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.SingleStepMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.continueExecutionMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.executeSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.loadMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.executeSeparator2 = new System.Windows.Forms.ToolStripSeparator();
            this.InterruptExecution = new System.Windows.Forms.ToolStripMenuItem();
            this.StopExec = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItem3 = new System.Windows.Forms.ToolStripSeparator();
            this.breakpointMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.breakpointExpressionMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.clearAllBreakpointsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItem1 = new System.Windows.Forms.ToolStripSeparator();
            this.traceMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.clearAllTracesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItem4 = new System.Windows.Forms.ToolStripSeparator();
            this.traceLoadMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.fKeyMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.advancedMenu = new System.Windows.Forms.ToolStripMenuItem();
            this.beginnerModeMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.tailRecursionMenu = new System.Windows.Forms.ToolStripMenuItem();
            this.fullTailRecursionMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.selfTailRecursionMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.noTailRecursionMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.debugSubmenu = new System.Windows.Forms.ToolStripMenuItem();
            this.showDetailMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.editorSubmenu = new System.Windows.Forms.ToolStripMenuItem();
            this.speedUpEditorMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.wizardSubmenu = new System.Windows.Forms.ToolStripMenuItem();
            this.lowLevelDebugMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.forceGCMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.windowsMenu = new System.Windows.Forms.ToolStripMenuItem();
            this.zoomMenu = new System.Windows.Forms.ToolStripMenuItem();
            this.zoom300 = new System.Windows.Forms.ToolStripMenuItem();
            this.zoom200 = new System.Windows.Forms.ToolStripMenuItem();
            this.zoom150 = new System.Windows.Forms.ToolStripMenuItem();
            this.zoom120 = new System.Windows.Forms.ToolStripMenuItem();
            this.zoom110 = new System.Windows.Forms.ToolStripMenuItem();
            this.zoom100 = new System.Windows.Forms.ToolStripMenuItem();
            this.zoom90 = new System.Windows.Forms.ToolStripMenuItem();
            this.zoom80 = new System.Windows.Forms.ToolStripMenuItem();
            this.RecenterMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.GotoMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.HelpMenu = new System.Windows.Forms.ToolStripMenuItem();
            this.examplesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.searchMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.helpSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.CheckMenu = new System.Windows.Forms.ToolStripMenuItem();
            this.CheckMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.AutoCheckMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.printDialog1 = new System.Windows.Forms.PrintDialog();
            this.statusBar = new System.Windows.Forms.StatusBar();
            this.valuePanel = new System.Windows.Forms.StatusBarPanel();
            this.arglistPanel = new System.Windows.Forms.StatusBarPanel();
            this.contextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.contextCut = new System.Windows.Forms.ToolStripMenuItem();
            this.contextCopy = new System.Windows.Forms.ToolStripMenuItem();
            this.contextPaste = new System.Windows.Forms.ToolStripMenuItem();
            this.contextSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.contextExecute = new System.Windows.Forms.ToolStripMenuItem();
            this.contextSingleStep = new System.Windows.Forms.ToolStripMenuItem();
            this.contextInspect = new System.Windows.Forms.ToolStripMenuItem();
            this.contextContinueExecutionMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.contextSeparator2 = new System.Windows.Forms.ToolStripSeparator();
            this.contextTrace = new System.Windows.Forms.ToolStripMenuItem();
            this.contextBreakpoint = new System.Windows.Forms.ToolStripMenuItem();
            this.contextBreakpointExpressionMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItem7 = new System.Windows.Forms.ToolStripSeparator();
            this.traceAnalysisMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.contextSeparator3 = new System.Windows.Forms.ToolStripSeparator();
            this.contextFindDefinition = new System.Windows.Forms.ToolStripMenuItem();
            this.contextFindUsesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.mainMenu.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.valuePanel)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.arglistPanel)).BeginInit();
            this.contextMenu.SuspendLayout();
            this.SuspendLayout();
            // 
            // mainMenu
            // 
            this.mainMenu.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.File,
            this.Edit,
            this.formatMenu,
            this.styleMenu,
            this.Execute,
            this.fKeyMenuItem,
            this.advancedMenu,
            this.windowsMenu,
            this.GotoMenuItem,
            this.HelpMenu,
            this.CheckMenu});
            this.mainMenu.Location = new System.Drawing.Point(0, 0);
            this.mainMenu.Name = "mainMenu";
            this.mainMenu.Padding = new System.Windows.Forms.Padding(2, 2, 0, 2);
            this.mainMenu.Size = new System.Drawing.Size(600, 24);
            this.mainMenu.TabIndex = 1;
            // 
            // File
            // 
            this.File.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.FileNew,
            this.FileOpen,
            this.FileClose,
            this.fileSeparator1,
            this.FileSave,
            this.FileSaveAs,
            this.setDefaultMenuItem,
            this.fileSeparator2,
            this.FilePrint,
            this.PreviewMenu,
            this.PrinterSettingsMenu,
            this.fileSeparator3,
            this.FileExit});
            this.File.MergeIndex = 0;
            this.File.Name = "File";
            this.File.Size = new System.Drawing.Size(37, 20);
            this.File.Text = "&File";
            // 
            // FileNew
            // 
            this.FileNew.MergeIndex = 0;
            this.FileNew.Name = "FileNew";
            this.FileNew.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
            this.FileNew.Size = new System.Drawing.Size(195, 22);
            this.FileNew.Text = "&New";
            this.FileNew.Click += new System.EventHandler(this.FileNew_Click);
            // 
            // FileOpen
            // 
            this.FileOpen.MergeIndex = 1;
            this.FileOpen.Name = "FileOpen";
            this.FileOpen.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
            this.FileOpen.Size = new System.Drawing.Size(195, 22);
            this.FileOpen.Text = "&Open";
            this.FileOpen.Click += new System.EventHandler(this.FileOpen_Click);
            // 
            // FileClose
            // 
            this.FileClose.MergeIndex = 2;
            this.FileClose.Name = "FileClose";
            this.FileClose.Size = new System.Drawing.Size(195, 22);
            this.FileClose.Text = "Close";
            this.FileClose.Click += new System.EventHandler(this.FileClose_Click);
            // 
            // fileSeparator1
            // 
            this.fileSeparator1.MergeIndex = 3;
            this.fileSeparator1.Name = "fileSeparator1";
            this.fileSeparator1.Size = new System.Drawing.Size(192, 6);
            // 
            // FileSave
            // 
            this.FileSave.MergeIndex = 4;
            this.FileSave.Name = "FileSave";
            this.FileSave.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
            this.FileSave.Size = new System.Drawing.Size(195, 22);
            this.FileSave.Text = "&Save";
            this.FileSave.Click += new System.EventHandler(this.FileSave_Click);
            // 
            // FileSaveAs
            // 
            this.FileSaveAs.MergeIndex = 5;
            this.FileSaveAs.Name = "FileSaveAs";
            this.FileSaveAs.Size = new System.Drawing.Size(195, 22);
            this.FileSaveAs.Text = "Save As...";
            this.FileSaveAs.Click += new System.EventHandler(this.FileSaveAs_Click);
            // 
            // setDefaultMenuItem
            // 
            this.setDefaultMenuItem.MergeIndex = 6;
            this.setDefaultMenuItem.Name = "setDefaultMenuItem";
            this.setDefaultMenuItem.Size = new System.Drawing.Size(195, 22);
            this.setDefaultMenuItem.Text = "Save as default settings";
            this.setDefaultMenuItem.ToolTipText = "Same settings from Style and Advanced menu";
            this.setDefaultMenuItem.Click += new System.EventHandler(this.setDefaultMenuItem_Click);
            // 
            // fileSeparator2
            // 
            this.fileSeparator2.MergeIndex = 7;
            this.fileSeparator2.Name = "fileSeparator2";
            this.fileSeparator2.Size = new System.Drawing.Size(192, 6);
            // 
            // FilePrint
            // 
            this.FilePrint.MergeIndex = 8;
            this.FilePrint.Name = "FilePrint";
            this.FilePrint.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P)));
            this.FilePrint.Size = new System.Drawing.Size(195, 22);
            this.FilePrint.Text = "&Print ...";
            this.FilePrint.Click += new System.EventHandler(this.FilePrint_Click);
            // 
            // PreviewMenu
            // 
            this.PreviewMenu.MergeIndex = 9;
            this.PreviewMenu.Name = "PreviewMenu";
            this.PreviewMenu.Size = new System.Drawing.Size(195, 22);
            this.PreviewMenu.Text = "Print Preview";
            this.PreviewMenu.Click += new System.EventHandler(this.PreviewMenu_Click);
            // 
            // PrinterSettingsMenu
            // 
            this.PrinterSettingsMenu.MergeIndex = 10;
            this.PrinterSettingsMenu.Name = "PrinterSettingsMenu";
            this.PrinterSettingsMenu.Size = new System.Drawing.Size(195, 22);
            this.PrinterSettingsMenu.Text = "Printer Settings";
            this.PrinterSettingsMenu.Click += new System.EventHandler(this.PrinterSettingsMenu_Click);
            // 
            // fileSeparator3
            // 
            this.fileSeparator3.MergeIndex = 11;
            this.fileSeparator3.Name = "fileSeparator3";
            this.fileSeparator3.Size = new System.Drawing.Size(192, 6);
            // 
            // FileExit
            // 
            this.FileExit.MergeIndex = 12;
            this.FileExit.Name = "FileExit";
            this.FileExit.Size = new System.Drawing.Size(195, 22);
            this.FileExit.Text = "E&xit";
            this.FileExit.Click += new System.EventHandler(this.FileExit_Click);
            // 
            // Edit
            // 
            this.Edit.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.undoMenuItem,
            this.editSeparator1,
            this.Cut,
            this.Copy,
            this.Paste,
            this.SelectAll,
            this.editSeparator2,
            this.transposeMenuItem,
            this.editSeparator3,
            this.pasteCommandMenuItem,
            this.pasteNextCommandMenuItem,
            this.menuItem5,
            this.findUnbalancedMenuItem,
            this.editSeparator4,
            this.ISearchMenuItem,
            this.findMenuItem,
            this.ReplaceMenuItem,
            this.menuItem6,
            this.FindDefinitionMenuItem,
            this.ShowReferencesMenuItem,
            this.ShowReferencesMenuItem2});
            this.Edit.MergeIndex = 1;
            this.Edit.Name = "Edit";
            this.Edit.Size = new System.Drawing.Size(39, 20);
            this.Edit.Text = "&Edit";
            this.Edit.DropDownOpening += new System.EventHandler(this.EditMenu_Pop);
            // 
            // undoMenuItem
            // 
            this.undoMenuItem.MergeIndex = 0;
            this.undoMenuItem.Name = "undoMenuItem";
            this.undoMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
            this.undoMenuItem.Size = new System.Drawing.Size(253, 22);
            this.undoMenuItem.Text = "Undo";
            this.undoMenuItem.Click += new System.EventHandler(this.Undo_Click);
            // 
            // editSeparator1
            // 
            this.editSeparator1.MergeIndex = 1;
            this.editSeparator1.Name = "editSeparator1";
            this.editSeparator1.Size = new System.Drawing.Size(250, 6);
            // 
            // Cut
            // 
            this.Cut.MergeIndex = 2;
            this.Cut.Name = "Cut";
            this.Cut.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
            this.Cut.Size = new System.Drawing.Size(253, 22);
            this.Cut.Text = "Cut";
            this.Cut.Click += new System.EventHandler(this.Cut_Click);
            // 
            // Copy
            // 
            this.Copy.MergeIndex = 3;
            this.Copy.Name = "Copy";
            this.Copy.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
            this.Copy.Size = new System.Drawing.Size(253, 22);
            this.Copy.Text = "Copy";
            this.Copy.Click += new System.EventHandler(this.Copy_Click);
            // 
            // Paste
            // 
            this.Paste.MergeIndex = 4;
            this.Paste.Name = "Paste";
            this.Paste.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
            this.Paste.Size = new System.Drawing.Size(253, 22);
            this.Paste.Text = "Paste";
            this.Paste.Click += new System.EventHandler(this.Paste_Click);
            // 
            // SelectAll
            // 
            this.SelectAll.MergeIndex = 5;
            this.SelectAll.Name = "SelectAll";
            this.SelectAll.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A)));
            this.SelectAll.Size = new System.Drawing.Size(253, 22);
            this.SelectAll.Text = "Select &All";
            this.SelectAll.Click += new System.EventHandler(this.SelectAll_Click);
            // 
            // editSeparator2
            // 
            this.editSeparator2.MergeIndex = 6;
            this.editSeparator2.Name = "editSeparator2";
            this.editSeparator2.Size = new System.Drawing.Size(250, 6);
            // 
            // transposeMenuItem
            // 
            this.transposeMenuItem.MergeIndex = 7;
            this.transposeMenuItem.Name = "transposeMenuItem";
            this.transposeMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Alt)
                        | System.Windows.Forms.Keys.T)));
            this.transposeMenuItem.Size = new System.Drawing.Size(253, 22);
            this.transposeMenuItem.Text = "Transpose expressions";
            this.transposeMenuItem.ToolTipText = "Swap the expression before the cursor with the expression after it";
            this.transposeMenuItem.Click += new System.EventHandler(this.Transpose_Click);
            // 
            // editSeparator3
            // 
            this.editSeparator3.MergeIndex = 8;
            this.editSeparator3.Name = "editSeparator3";
            this.editSeparator3.Size = new System.Drawing.Size(250, 6);
            // 
            // pasteCommandMenuItem
            // 
            this.pasteCommandMenuItem.MergeIndex = 9;
            this.pasteCommandMenuItem.Name = "pasteCommandMenuItem";
            this.pasteCommandMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Up)));
            this.pasteCommandMenuItem.Size = new System.Drawing.Size(253, 22);
            this.pasteCommandMenuItem.Text = "Paste &Previous command";
            this.pasteCommandMenuItem.ToolTipText = "Retypes the last expression you executed.\r\nRepeated use of command moves to earli" +
                "er expressions";
            this.pasteCommandMenuItem.Click += new System.EventHandler(this.pasteCommandMenuItem_Click);
            // 
            // pasteNextCommandMenuItem
            // 
            this.pasteNextCommandMenuItem.MergeIndex = 10;
            this.pasteNextCommandMenuItem.Name = "pasteNextCommandMenuItem";
            this.pasteNextCommandMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Down)));
            this.pasteNextCommandMenuItem.Size = new System.Drawing.Size(253, 22);
            this.pasteNextCommandMenuItem.Text = "Paste &Next command";
            this.pasteNextCommandMenuItem.ToolTipText = "Reverses the effect of Control-up arrow";
            this.pasteNextCommandMenuItem.Click += new System.EventHandler(this.menuItem8_Click);
            // 
            // menuItem5
            // 
            this.menuItem5.MergeIndex = 11;
            this.menuItem5.Name = "menuItem5";
            this.menuItem5.Size = new System.Drawing.Size(250, 6);
            // 
            // findUnbalancedMenuItem
            // 
            this.findUnbalancedMenuItem.MergeIndex = 12;
            this.findUnbalancedMenuItem.Name = "findUnbalancedMenuItem";
            this.findUnbalancedMenuItem.Size = new System.Drawing.Size(253, 22);
            this.findUnbalancedMenuItem.Text = "Find &unbalanced brackets";
            this.findUnbalancedMenuItem.ToolTipText = "Move cursor to expression with unbalanced brackets, parentheses, or quote marks (" +
                "if any)";
            this.findUnbalancedMenuItem.Click += new System.EventHandler(this.ReindentAllMenuItem_Click);
            // 
            // editSeparator4
            // 
            this.editSeparator4.MergeIndex = 13;
            this.editSeparator4.Name = "editSeparator4";
            this.editSeparator4.Size = new System.Drawing.Size(250, 6);
            this.editSeparator4.Click += new System.EventHandler(this.Transpose_Click);
            // 
            // ISearchMenuItem
            // 
            this.ISearchMenuItem.MergeIndex = 14;
            this.ISearchMenuItem.Name = "ISearchMenuItem";
            this.ISearchMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.S)));
            this.ISearchMenuItem.Size = new System.Drawing.Size(253, 22);
            this.ISearchMenuItem.Text = "&Incremental search ...";
            this.ISearchMenuItem.Click += new System.EventHandler(this.ISearchMenuItem_Click);
            // 
            // findMenuItem
            // 
            this.findMenuItem.MergeIndex = 15;
            this.findMenuItem.Name = "findMenuItem";
            this.findMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F)));
            this.findMenuItem.Size = new System.Drawing.Size(253, 22);
            this.findMenuItem.Text = "&Find ...";
            this.findMenuItem.Click += new System.EventHandler(this.findMenuItem_Click);
            // 
            // ReplaceMenuItem
            // 
            this.ReplaceMenuItem.MergeIndex = 16;
            this.ReplaceMenuItem.Name = "ReplaceMenuItem";
            this.ReplaceMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.H)));
            this.ReplaceMenuItem.Size = new System.Drawing.Size(253, 22);
            this.ReplaceMenuItem.Text = "&Replace ...";
            this.ReplaceMenuItem.Click += new System.EventHandler(this.ReplaceMenuItem_Click);
            // 
            // menuItem6
            // 
            this.menuItem6.MergeIndex = 17;
            this.menuItem6.Name = "menuItem6";
            this.menuItem6.Size = new System.Drawing.Size(250, 6);
            // 
            // FindDefinitionMenuItem
            // 
            this.FindDefinitionMenuItem.MergeIndex = 18;
            this.FindDefinitionMenuItem.Name = "FindDefinitionMenuItem";
            this.FindDefinitionMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D)));
            this.FindDefinitionMenuItem.Size = new System.Drawing.Size(253, 22);
            this.FindDefinitionMenuItem.Text = "Find &Definition";
            this.FindDefinitionMenuItem.ToolTipText = "Find the definition of the selected variable";
            this.FindDefinitionMenuItem.Click += new System.EventHandler(this.FindDefinition_Click);
            // 
            // ShowReferencesMenuItem
            // 
            this.ShowReferencesMenuItem.MergeIndex = 19;
            this.ShowReferencesMenuItem.Name = "ShowReferencesMenuItem";
            this.ShowReferencesMenuItem.Size = new System.Drawing.Size(253, 22);
            this.ShowReferencesMenuItem.Text = "&Show references";
            this.ShowReferencesMenuItem.ToolTipText = "Show a menu of procedures that use this variable";
            this.ShowReferencesMenuItem.Click += new System.EventHandler(this.ShowReferences_Click);
            // 
            // ShowReferencesMenuItem2
            // 
            this.ShowReferencesMenuItem2.MergeIndex = 20;
            this.ShowReferencesMenuItem2.Name = "ShowReferencesMenuItem2";
            this.ShowReferencesMenuItem2.Size = new System.Drawing.Size(253, 22);
            this.ShowReferencesMenuItem2.Text = "Show &references";
            this.ShowReferencesMenuItem2.ToolTipText = "Show a menu of procedures that use this variable";
            this.ShowReferencesMenuItem2.Click += new System.EventHandler(this.ShowReferences2_Click);
            // 
            // formatMenu
            // 
            this.formatMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.fontMenuItem,
            this.formatSeparator1,
            this.formatBold,
            this.formatItalic,
            this.formatBullet,
            this.formatSeparator2,
            this.formatGrow,
            this.formatShrink,
            this.formatSeparator3,
            this.formatSubscript,
            this.formatSuperscript,
            this.formatSeparator4,
            this.backgroundColorMenuItem,
            this.reindentMenuItem,
            this.reindentAllMenuItem,
            this.RemoveWhitespaceMenuItem});
            this.formatMenu.MergeIndex = 2;
            this.formatMenu.Name = "formatMenu";
            this.formatMenu.Size = new System.Drawing.Size(55, 20);
            this.formatMenu.Text = "F&ormat";
            this.formatMenu.ToolTipText = "Use Reindent to fix reindenting of an expression";
            this.formatMenu.DropDownOpening += new System.EventHandler(this.FormatMenuPop);
            // 
            // fontMenuItem
            // 
            this.fontMenuItem.MergeIndex = 0;
            this.fontMenuItem.Name = "fontMenuItem";
            this.fontMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.F)));
            this.fontMenuItem.Size = new System.Drawing.Size(219, 22);
            this.fontMenuItem.Text = "&Font ...";
            this.fontMenuItem.ToolTipText = "Adjusts font, size, and color of selected text";
            this.fontMenuItem.Click += new System.EventHandler(this.Font_Click);
            // 
            // formatSeparator1
            // 
            this.formatSeparator1.MergeIndex = 1;
            this.formatSeparator1.Name = "formatSeparator1";
            this.formatSeparator1.Size = new System.Drawing.Size(216, 6);
            // 
            // formatBold
            // 
            this.formatBold.MergeIndex = 2;
            this.formatBold.Name = "formatBold";
            this.formatBold.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.B)));
            this.formatBold.Size = new System.Drawing.Size(219, 22);
            this.formatBold.Text = "&Bold";
            this.formatBold.Click += new System.EventHandler(this.FormatBoldClick);
            // 
            // formatItalic
            // 
            this.formatItalic.MergeIndex = 3;
            this.formatItalic.Name = "formatItalic";
            this.formatItalic.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.I)));
            this.formatItalic.Size = new System.Drawing.Size(219, 22);
            this.formatItalic.Text = "&Italic";
            this.formatItalic.Click += new System.EventHandler(this.FormatItalicClick);
            // 
            // formatBullet
            // 
            this.formatBullet.MergeIndex = 4;
            this.formatBullet.Name = "formatBullet";
            this.formatBullet.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.L)));
            this.formatBullet.Size = new System.Drawing.Size(219, 22);
            this.formatBullet.Text = "Bullet";
            this.formatBullet.Click += new System.EventHandler(this.FormatBulletClick);
            // 
            // formatSeparator2
            // 
            this.formatSeparator2.MergeIndex = 5;
            this.formatSeparator2.Name = "formatSeparator2";
            this.formatSeparator2.Size = new System.Drawing.Size(216, 6);
            // 
            // formatGrow
            // 
            this.formatGrow.MergeIndex = 6;
            this.formatGrow.Name = "formatGrow";
            this.formatGrow.ShortcutKeyDisplayString = "Ctrl+Shift+>";
            this.formatGrow.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.OemPeriod)));
            this.formatGrow.Size = new System.Drawing.Size(219, 22);
            this.formatGrow.Text = "Grow font";
            this.formatGrow.ToolTipText = "Changes selected text to be larger";
            this.formatGrow.Click += new System.EventHandler(this.FormatGrowClick);
            // 
            // formatShrink
            // 
            this.formatShrink.MergeIndex = 7;
            this.formatShrink.Name = "formatShrink";
            this.formatShrink.ShortcutKeyDisplayString = "Ctrol+Shift+<";
            this.formatShrink.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.Oemcomma)));
            this.formatShrink.Size = new System.Drawing.Size(219, 22);
            this.formatShrink.Text = "Shrink font";
            this.formatShrink.ToolTipText = "Changes selected text to be smaller";
            this.formatShrink.Click += new System.EventHandler(this.FormatShrinkClick);
            // 
            // formatSeparator3
            // 
            this.formatSeparator3.MergeIndex = 8;
            this.formatSeparator3.Name = "formatSeparator3";
            this.formatSeparator3.Size = new System.Drawing.Size(216, 6);
            // 
            // formatSubscript
            // 
            this.formatSubscript.MergeIndex = 9;
            this.formatSubscript.Name = "formatSubscript";
            this.formatSubscript.ShortcutKeyDisplayString = "Ctrl+Shift+ +";
            this.formatSubscript.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Oemplus)));
            this.formatSubscript.Size = new System.Drawing.Size(219, 22);
            this.formatSubscript.Text = "Superscript";
            this.formatSubscript.ToolTipText = "Converts selected text to be a superscript";
            this.formatSubscript.Click += new System.EventHandler(this.FormatSuperscriptClick);
            // 
            // formatSuperscript
            // 
            this.formatSuperscript.MergeIndex = 10;
            this.formatSuperscript.Name = "formatSuperscript";
            this.formatSuperscript.ShortcutKeyDisplayString = "Ctrl+Shift+=";
            this.formatSuperscript.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Oemplus)));
            this.formatSuperscript.Size = new System.Drawing.Size(219, 22);
            this.formatSuperscript.Text = "Subscript";
            this.formatSuperscript.ToolTipText = "Converts selected text to be a subscript";
            this.formatSuperscript.Click += new System.EventHandler(this.FormatSubscriptClick);
            // 
            // formatSeparator4
            // 
            this.formatSeparator4.MergeIndex = 11;
            this.formatSeparator4.Name = "formatSeparator4";
            this.formatSeparator4.Size = new System.Drawing.Size(216, 6);
            // 
            // backgroundColorMenuItem
            // 
            this.backgroundColorMenuItem.MergeIndex = 12;
            this.backgroundColorMenuItem.Name = "backgroundColorMenuItem";
            this.backgroundColorMenuItem.Size = new System.Drawing.Size(219, 22);
            this.backgroundColorMenuItem.Text = "Background &color ...";
            this.backgroundColorMenuItem.Click += new System.EventHandler(this.backgroundColorMenuItem_Click);
            // 
            // reindentMenuItem
            // 
            this.reindentMenuItem.MergeIndex = 13;
            this.reindentMenuItem.Name = "reindentMenuItem";
            this.reindentMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.R)));
            this.reindentMenuItem.Size = new System.Drawing.Size(219, 22);
            this.reindentMenuItem.Text = "&Reindent";
            this.reindentMenuItem.ToolTipText = "Fixes the indenting of the current expression";
            this.reindentMenuItem.Click += new System.EventHandler(this.ReindentMenuItem_Click);
            // 
            // reindentAllMenuItem
            // 
            this.reindentAllMenuItem.MergeIndex = 14;
            this.reindentAllMenuItem.Name = "reindentAllMenuItem";
            this.reindentAllMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.R)));
            this.reindentAllMenuItem.Size = new System.Drawing.Size(219, 22);
            this.reindentAllMenuItem.Text = "Reindent &all";
            this.reindentAllMenuItem.ToolTipText = "Fixes the indenting of all expressions in this file";
            this.reindentAllMenuItem.Click += new System.EventHandler(this.ReindentAllMenuItem_Click);
            // 
            // RemoveWhitespaceMenuItem
            // 
            this.RemoveWhitespaceMenuItem.MergeIndex = 15;
            this.RemoveWhitespaceMenuItem.Name = "RemoveWhitespaceMenuItem";
            this.RemoveWhitespaceMenuItem.Size = new System.Drawing.Size(219, 22);
            this.RemoveWhitespaceMenuItem.Text = "Remove &Leading whitespace";
            this.RemoveWhitespaceMenuItem.ToolTipText = "Removes spaces and tabs at the beginning of lines. \r\nUsed when importing scheme c" +
                "ode created in other text editors.";
            this.RemoveWhitespaceMenuItem.Click += new System.EventHandler(this.RemoveWhitespaceMenuItem_Click);
            // 
            // styleMenu
            // 
            this.styleMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.editStylesMenuItem,
            this.styleSeparator1,
            this.NormalStyleMenuItem,
            this.TitleStyleMenuItem,
            this.CommentStyleMenuItem,
            this.menuItem2,
            this.restyleMenuItem,
            this.restyleAllMenuItem,
            this.restyleAllPreservingCommentsMenuItem});
            this.styleMenu.MergeIndex = 3;
            this.styleMenu.Name = "styleMenu";
            this.styleMenu.Size = new System.Drawing.Size(43, 20);
            this.styleMenu.Text = "&Style";
            this.styleMenu.ToolTipText = "Use restyle to quickly fix the fonts of an expression";
            // 
            // editStylesMenuItem
            // 
            this.editStylesMenuItem.MergeIndex = 0;
            this.editStylesMenuItem.Name = "editStylesMenuItem";
            this.editStylesMenuItem.Size = new System.Drawing.Size(252, 22);
            this.editStylesMenuItem.Text = "Edit styles";
            this.editStylesMenuItem.ToolTipText = "Change the font, size, and colors of the standard styles";
            this.editStylesMenuItem.Click += new System.EventHandler(this.EditStyles_Click);
            // 
            // styleSeparator1
            // 
            this.styleSeparator1.MergeIndex = 1;
            this.styleSeparator1.Name = "styleSeparator1";
            this.styleSeparator1.Size = new System.Drawing.Size(249, 6);
            // 
            // NormalStyleMenuItem
            // 
            this.NormalStyleMenuItem.MergeIndex = 2;
            this.NormalStyleMenuItem.Name = "NormalStyleMenuItem";
            this.NormalStyleMenuItem.Size = new System.Drawing.Size(252, 22);
            this.NormalStyleMenuItem.Text = "&Normal";
            this.NormalStyleMenuItem.ToolTipText = "Change selected text to the normal style";
            this.NormalStyleMenuItem.Click += new System.EventHandler(this.ApplyStyle);
            // 
            // TitleStyleMenuItem
            // 
            this.TitleStyleMenuItem.MergeIndex = 3;
            this.TitleStyleMenuItem.Name = "TitleStyleMenuItem";
            this.TitleStyleMenuItem.Size = new System.Drawing.Size(252, 22);
            this.TitleStyleMenuItem.Text = "&Title";
            this.TitleStyleMenuItem.ToolTipText = "Change the selected text to the style used for variable names in definitions";
            this.TitleStyleMenuItem.Click += new System.EventHandler(this.ApplyStyle);
            // 
            // CommentStyleMenuItem
            // 
            this.CommentStyleMenuItem.MergeIndex = 4;
            this.CommentStyleMenuItem.Name = "CommentStyleMenuItem";
            this.CommentStyleMenuItem.Size = new System.Drawing.Size(252, 22);
            this.CommentStyleMenuItem.Text = "&Comment";
            this.CommentStyleMenuItem.ToolTipText = "Change the selected text to be in the style of comments";
            this.CommentStyleMenuItem.Click += new System.EventHandler(this.ApplyStyle);
            // 
            // menuItem2
            // 
            this.menuItem2.MergeIndex = 5;
            this.menuItem2.Name = "menuItem2";
            this.menuItem2.Size = new System.Drawing.Size(249, 6);
            // 
            // restyleMenuItem
            // 
            this.restyleMenuItem.MergeIndex = 6;
            this.restyleMenuItem.Name = "restyleMenuItem";
            this.restyleMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Alt)
                        | System.Windows.Forms.Keys.R)));
            this.restyleMenuItem.Size = new System.Drawing.Size(252, 22);
            this.restyleMenuItem.Text = "&Restyle this expression";
            this.restyleMenuItem.ToolTipText = "Reset styles of this expression as if you were retyping it";
            this.restyleMenuItem.Click += new System.EventHandler(this.restyleMenuItem_Click);
            // 
            // restyleAllMenuItem
            // 
            this.restyleAllMenuItem.MergeIndex = 7;
            this.restyleAllMenuItem.Name = "restyleAllMenuItem";
            this.restyleAllMenuItem.Size = new System.Drawing.Size(252, 22);
            this.restyleAllMenuItem.Text = "Restyle &all, including comments";
            this.restyleAllMenuItem.ToolTipText = "Fix the styles of all the text in the file";
            this.restyleAllMenuItem.Click += new System.EventHandler(this.restyleAllMenuItem_Click);
            // 
            // restyleAllPreservingCommentsMenuItem
            // 
            this.restyleAllPreservingCommentsMenuItem.MergeIndex = 8;
            this.restyleAllPreservingCommentsMenuItem.Name = "restyleAllPreservingCommentsMenuItem";
            this.restyleAllPreservingCommentsMenuItem.Size = new System.Drawing.Size(252, 22);
            this.restyleAllPreservingCommentsMenuItem.Text = "Restyle all, &preserving comments";
            this.restyleAllPreservingCommentsMenuItem.ToolTipText = "Fix the styles of all the text in the file except for comments";
            this.restyleAllPreservingCommentsMenuItem.Click += new System.EventHandler(this.restyleAllPreservingCommentsMenuItem_Click);
            // 
            // Execute
            // 
            this.Execute.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.Evaluate,
            this.inspectMenuItem,
            this.executeSelectionMenuItem,
            this.executeAllMenuItem,
            this.SingleStepMenuItem,
            this.continueExecutionMenuItem,
            this.executeSeparator1,
            this.loadMenuItem,
            this.executeSeparator2,
            this.InterruptExecution,
            this.StopExec,
            this.menuItem3,
            this.breakpointMenuItem,
            this.breakpointExpressionMenuItem,
            this.clearAllBreakpointsMenuItem,
            this.menuItem1,
            this.traceMenuItem,
            this.clearAllTracesMenuItem,
            this.menuItem4,
            this.traceLoadMenuItem});
            this.Execute.MergeIndex = 4;
            this.Execute.Name = "Execute";
            this.Execute.Size = new System.Drawing.Size(58, 20);
            this.Execute.Text = "E&xecute";
            this.Execute.ToolTipText = "Use this menu to run code or to change the way code is run";
            this.Execute.DropDownOpening += new System.EventHandler(this.MenuPop_Execute);
            // 
            // Evaluate
            // 
            this.Evaluate.MergeIndex = 0;
            this.Evaluate.Name = "Evaluate";
            this.Evaluate.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.E)));
            this.Evaluate.Size = new System.Drawing.Size(249, 22);
            this.Evaluate.Text = "&Execute";
            this.Evaluate.ToolTipText = "Run the definition surrounding the cursor\r\nIf the cursor isn\'t in a definition (i" +
                ".e. isn\'t in\r\nsomething like [define var value]), then this\r\nwill run whatever t" +
                "op-level expression the\r\ncursor is in.";
            this.Evaluate.Click += new System.EventHandler(this.Evaluate_Click);
            // 
            // inspectMenuItem
            // 
            this.inspectMenuItem.MergeIndex = 1;
            this.inspectMenuItem.Name = "inspectMenuItem";
            this.inspectMenuItem.Size = new System.Drawing.Size(249, 22);
            this.inspectMenuItem.Text = "Execute and &Inspect result";
            this.inspectMenuItem.ToolTipText = "Same as execute, but lets you examine\r\nthe return value using the inspector";
            this.inspectMenuItem.Click += new System.EventHandler(this.Inspect_Click);
            // 
            // executeSelectionMenuItem
            // 
            this.executeSelectionMenuItem.MergeIndex = 2;
            this.executeSelectionMenuItem.Name = "executeSelectionMenuItem";
            this.executeSelectionMenuItem.Size = new System.Drawing.Size(249, 22);
            this.executeSelectionMenuItem.Text = "Execute &Selection";
            this.executeSelectionMenuItem.ToolTipText = "Runs whatever text is selected";
            this.executeSelectionMenuItem.Click += new System.EventHandler(this.EvalRegion_Click);
            // 
            // executeAllMenuItem
            // 
            this.executeAllMenuItem.MergeIndex = 3;
            this.executeAllMenuItem.Name = "executeAllMenuItem";
            this.executeAllMenuItem.Size = new System.Drawing.Size(249, 22);
            this.executeAllMenuItem.Text = "Execute &All";
            this.executeAllMenuItem.ToolTipText = "Runs all code in the file, starting\r\nfrom the beginning.";
            this.executeAllMenuItem.Click += new System.EventHandler(this.EvalFile_Click);
            // 
            // SingleStepMenuItem
            // 
            this.SingleStepMenuItem.MergeIndex = 4;
            this.SingleStepMenuItem.Name = "SingleStepMenuItem";
            this.SingleStepMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D1)));
            this.SingleStepMenuItem.Size = new System.Drawing.Size(249, 22);
            this.SingleStepMenuItem.Text = "Execute &1 Step";
            this.SingleStepMenuItem.ToolTipText = "Starts execution of the current expression\r\nbut pauses inside the debugger so you" +
                " can\r\nsingle-step execution.";
            this.SingleStepMenuItem.Click += new System.EventHandler(this.SingleStep_Click);
            // 
            // continueExecutionMenuItem
            // 
            this.continueExecutionMenuItem.MergeIndex = 5;
            this.continueExecutionMenuItem.Name = "continueExecutionMenuItem";
            this.continueExecutionMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F12;
            this.continueExecutionMenuItem.Size = new System.Drawing.Size(249, 22);
            this.continueExecutionMenuItem.Text = "&Continue execution to here";
            this.continueExecutionMenuItem.ToolTipText = "Used when single-stepping or breakpointing.\r\nContinues execution until the progra" +
                "m reaches\r\nthe current expression.";
            this.continueExecutionMenuItem.Click += new System.EventHandler(this.continueExecutionMenuItem_Click);
            // 
            // executeSeparator1
            // 
            this.executeSeparator1.MergeIndex = 6;
            this.executeSeparator1.Name = "executeSeparator1";
            this.executeSeparator1.Size = new System.Drawing.Size(246, 6);
            // 
            // loadMenuItem
            // 
            this.loadMenuItem.MergeIndex = 7;
            this.loadMenuItem.Name = "loadMenuItem";
            this.loadMenuItem.Size = new System.Drawing.Size(249, 22);
            this.loadMenuItem.Text = "Load file ...";
            this.loadMenuItem.ToolTipText = "Runs all expressions in a file without\r\nopening it as an editor window.";
            this.loadMenuItem.Click += new System.EventHandler(this.loadMenuItem_Click);
            // 
            // executeSeparator2
            // 
            this.executeSeparator2.MergeIndex = 8;
            this.executeSeparator2.Name = "executeSeparator2";
            this.executeSeparator2.Size = new System.Drawing.Size(246, 6);
            // 
            // InterruptExecution
            // 
            this.InterruptExecution.MergeIndex = 9;
            this.InterruptExecution.Name = "InterruptExecution";
            this.InterruptExecution.Size = new System.Drawing.Size(249, 22);
            this.InterruptExecution.Text = "Interrupt execution";
            this.InterruptExecution.ToolTipText = "Pauses execution and show the stack in the debugger";
            this.InterruptExecution.Click += new System.EventHandler(this.InterruptExecution_Click);
            // 
            // StopExec
            // 
            this.StopExec.MergeIndex = 10;
            this.StopExec.Name = "StopExec";
            this.StopExec.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Delete)));
            this.StopExec.Size = new System.Drawing.Size(249, 22);
            this.StopExec.Text = "Abort execution";
            this.StopExec.ToolTipText = "Stops execution entirely.";
            this.StopExec.Click += new System.EventHandler(this.StopExec_Click);
            // 
            // menuItem3
            // 
            this.menuItem3.MergeIndex = 11;
            this.menuItem3.Name = "menuItem3";
            this.menuItem3.Size = new System.Drawing.Size(246, 6);
            // 
            // breakpointMenuItem
            // 
            this.breakpointMenuItem.MergeIndex = 12;
            this.breakpointMenuItem.Name = "breakpointMenuItem";
            this.breakpointMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.Delete)));
            this.breakpointMenuItem.Size = new System.Drawing.Size(249, 22);
            this.breakpointMenuItem.Text = "Breakpoint procedure";
            this.breakpointMenuItem.ToolTipText = "When checked, causes execution to\r\npause any time this procedure is called.\r\nThe " +
                "debugger will be displayed to let\r\nyou examine the stack and/or continue\r\nexecut" +
                "ion.";
            this.breakpointMenuItem.Click += new System.EventHandler(this.Breakpoint_Click);
            // 
            // breakpointExpressionMenuItem
            // 
            this.breakpointExpressionMenuItem.MergeIndex = 13;
            this.breakpointExpressionMenuItem.Name = "breakpointExpressionMenuItem";
            this.breakpointExpressionMenuItem.Size = new System.Drawing.Size(249, 22);
            this.breakpointExpressionMenuItem.Text = "Breakpoint expression";
            this.breakpointExpressionMenuItem.ToolTipText = "When checked, causes execution to\r\npause whenever it reaches this expression.\r\nTh" +
                "e debugger will be displayed to let\r\nyou examine the stack and/or continue\r\nexec" +
                "ution.";
            this.breakpointExpressionMenuItem.Click += new System.EventHandler(this.breakpointExpressionMenuItem_Click);
            // 
            // clearAllBreakpointsMenuItem
            // 
            this.clearAllBreakpointsMenuItem.MergeIndex = 14;
            this.clearAllBreakpointsMenuItem.Name = "clearAllBreakpointsMenuItem";
            this.clearAllBreakpointsMenuItem.Size = new System.Drawing.Size(249, 22);
            this.clearAllBreakpointsMenuItem.Text = "Clear all breakpoints";
            this.clearAllBreakpointsMenuItem.ToolTipText = "Cancels all pausing for procedures and expressions";
            this.clearAllBreakpointsMenuItem.Click += new System.EventHandler(this.clearAllBreakpointsMenuItem_Click);
            // 
            // menuItem1
            // 
            this.menuItem1.MergeIndex = 15;
            this.menuItem1.Name = "menuItem1";
            this.menuItem1.Size = new System.Drawing.Size(246, 6);
            // 
            // traceMenuItem
            // 
            this.traceMenuItem.MergeIndex = 16;
            this.traceMenuItem.Name = "traceMenuItem";
            this.traceMenuItem.Size = new System.Drawing.Size(249, 22);
            this.traceMenuItem.Text = "&Trace procedure";
            this.traceMenuItem.ToolTipText = "When checked, the system will log all\r\ncalls to this procedure, along with their\r" +
                "\ninput and output values.";
            this.traceMenuItem.Click += new System.EventHandler(this.Trace_Click);
            // 
            // clearAllTracesMenuItem
            // 
            this.clearAllTracesMenuItem.MergeIndex = 17;
            this.clearAllTracesMenuItem.Name = "clearAllTracesMenuItem";
            this.clearAllTracesMenuItem.Size = new System.Drawing.Size(249, 22);
            this.clearAllTracesMenuItem.Text = "Clear all traces";
            this.clearAllTracesMenuItem.ToolTipText = "Cancels all tracing of procedures.";
            this.clearAllTracesMenuItem.Click += new System.EventHandler(this.clearAllTracesMenuItem_Click);
            // 
            // menuItem4
            // 
            this.menuItem4.MergeIndex = 18;
            this.menuItem4.Name = "menuItem4";
            this.menuItem4.Size = new System.Drawing.Size(246, 6);
            // 
            // traceLoadMenuItem
            // 
            this.traceLoadMenuItem.MergeIndex = 19;
            this.traceLoadMenuItem.Name = "traceLoadMenuItem";
            this.traceLoadMenuItem.Size = new System.Drawing.Size(249, 22);
            this.traceLoadMenuItem.Text = "&Print all results when loading files";
            this.traceLoadMenuItem.ToolTipText = "When checked, the load command will print the \r\nresult of every expression in the" +
                " Interaction Window.";
            this.traceLoadMenuItem.Click += new System.EventHandler(this.traceLoadMenuItem_Click);
            // 
            // fKeyMenuItem
            // 
            this.fKeyMenuItem.MergeIndex = 5;
            this.fKeyMenuItem.Name = "fKeyMenuItem";
            this.fKeyMenuItem.Size = new System.Drawing.Size(60, 20);
            this.fKeyMenuItem.Text = "Hot&keys";
            this.fKeyMenuItem.ToolTipText = "Your program has defined procedures that\r\ncan be run automatically from this menu" +
                "";
            this.fKeyMenuItem.DropDownOpening += new System.EventHandler(this.FKeyMenuItem_Popup);
            // 
            // advancedMenu
            // 
            this.advancedMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.beginnerModeMenuItem,
            this.tailRecursionMenu,
            this.debugSubmenu,
            this.editorSubmenu,
            this.wizardSubmenu});
            this.advancedMenu.MergeIndex = 6;
            this.advancedMenu.Name = "advancedMenu";
            this.advancedMenu.Size = new System.Drawing.Size(69, 20);
            this.advancedMenu.Text = "&Advanced";
            this.advancedMenu.ToolTipText = "Enable or disable advanced features";
            this.advancedMenu.DropDownOpening += new System.EventHandler(this.MenuPop_Advanced);
            // 
            // beginnerModeMenuItem
            // 
            this.beginnerModeMenuItem.MergeIndex = 0;
            this.beginnerModeMenuItem.Name = "beginnerModeMenuItem";
            this.beginnerModeMenuItem.Size = new System.Drawing.Size(226, 22);
            this.beginnerModeMenuItem.Text = "Beginning programmer mode";
            this.beginnerModeMenuItem.ToolTipText = "Check this item to automatically enable\r\nthe 2D graphics package and to disable\r\n" +
                "tail-call optimization";
            this.beginnerModeMenuItem.Click += new System.EventHandler(this.beginnerModeMenuItem_Click);
            // 
            // tailRecursionMenu
            // 
            this.tailRecursionMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.fullTailRecursionMenuItem,
            this.selfTailRecursionMenuItem,
            this.noTailRecursionMenuItem});
            this.tailRecursionMenu.MergeIndex = 1;
            this.tailRecursionMenu.Name = "tailRecursionMenu";
            this.tailRecursionMenu.Size = new System.Drawing.Size(226, 22);
            this.tailRecursionMenu.Text = "Tail recursion";
            this.tailRecursionMenu.ToolTipText = resources.GetString("tailRecursionMenu.ToolTipText");
            this.tailRecursionMenu.DropDownOpening += new System.EventHandler(this.tailRecursionMenu_Popup);
            // 
            // fullTailRecursionMenuItem
            // 
            this.fullTailRecursionMenuItem.MergeIndex = 0;
            this.fullTailRecursionMenuItem.Name = "fullTailRecursionMenuItem";
            this.fullTailRecursionMenuItem.Size = new System.Drawing.Size(170, 22);
            this.fullTailRecursionMenuItem.Text = "Full optimization";
            this.fullTailRecursionMenuItem.ToolTipText = "Full tail-call optimization\r\nUse this if you want to optimize mutually\r\nrecursive" +
                " procedures.";
            this.fullTailRecursionMenuItem.Click += new System.EventHandler(this.fullTailRecursionMenuItem_Click);
            // 
            // selfTailRecursionMenuItem
            // 
            this.selfTailRecursionMenuItem.MergeIndex = 1;
            this.selfTailRecursionMenuItem.Name = "selfTailRecursionMenuItem";
            this.selfTailRecursionMenuItem.Size = new System.Drawing.Size(170, 22);
            this.selfTailRecursionMenuItem.Text = "Self-recursion only";
            this.selfTailRecursionMenuItem.ToolTipText = resources.GetString("selfTailRecursionMenuItem.ToolTipText");
            this.selfTailRecursionMenuItem.Click += new System.EventHandler(this.selfTailRecursionMenuItem_Click);
            // 
            // noTailRecursionMenuItem
            // 
            this.noTailRecursionMenuItem.MergeIndex = 2;
            this.noTailRecursionMenuItem.Name = "noTailRecursionMenuItem";
            this.noTailRecursionMenuItem.Size = new System.Drawing.Size(170, 22);
            this.noTailRecursionMenuItem.Text = "No optimization";
            this.noTailRecursionMenuItem.ToolTipText = "Tail-calls are never optimized\r\nThe stack will always show a faithful record\r\nof " +
                "the chain of callers of a given procedure.";
            this.noTailRecursionMenuItem.Click += new System.EventHandler(this.noTailRecursionMenuItem_Click);
            // 
            // debugSubmenu
            // 
            this.debugSubmenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.showDetailMenuItem});
            this.debugSubmenu.MergeIndex = 2;
            this.debugSubmenu.Name = "debugSubmenu";
            this.debugSubmenu.Size = new System.Drawing.Size(226, 22);
            this.debugSubmenu.Text = "&Debug";
            // 
            // showDetailMenuItem
            // 
            this.showDetailMenuItem.MergeIndex = 0;
            this.showDetailMenuItem.Name = "showDetailMenuItem";
            this.showDetailMenuItem.Size = new System.Drawing.Size(199, 22);
            this.showDetailMenuItem.Text = "Show &detail in inspector";
            this.showDetailMenuItem.ToolTipText = "Causes inspector to display private and internal members of objects";
            this.showDetailMenuItem.Click += new System.EventHandler(this.ShowDetail_Click);
            // 
            // editorSubmenu
            // 
            this.editorSubmenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.speedUpEditorMenuItem});
            this.editorSubmenu.MergeIndex = 3;
            this.editorSubmenu.Name = "editorSubmenu";
            this.editorSubmenu.Size = new System.Drawing.Size(226, 22);
            this.editorSubmenu.Text = "&Editor";
            // 
            // speedUpEditorMenuItem
            // 
            this.speedUpEditorMenuItem.MergeIndex = 0;
            this.speedUpEditorMenuItem.Name = "speedUpEditorMenuItem";
            this.speedUpEditorMenuItem.Size = new System.Drawing.Size(256, 22);
            this.speedUpEditorMenuItem.Text = "&Speed up editor (turns off features)";
            this.speedUpEditorMenuItem.Click += new System.EventHandler(this.SpeedUpEditor_Click);
            // 
            // wizardSubmenu
            // 
            this.wizardSubmenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.lowLevelDebugMenuItem,
            this.forceGCMenuItem});
            this.wizardSubmenu.MergeIndex = 4;
            this.wizardSubmenu.Name = "wizardSubmenu";
            this.wizardSubmenu.Size = new System.Drawing.Size(226, 22);
            this.wizardSubmenu.Text = "&Wizard";
            // 
            // lowLevelDebugMenuItem
            // 
            this.lowLevelDebugMenuItem.MergeIndex = 0;
            this.lowLevelDebugMenuItem.Name = "lowLevelDebugMenuItem";
            this.lowLevelDebugMenuItem.Size = new System.Drawing.Size(158, 22);
            this.lowLevelDebugMenuItem.Text = "&Low level debug";
            this.lowLevelDebugMenuItem.ToolTipText = "Used for debugging Meta itself\r\nDisables Meta\'s exception handlers, forcing\r\nexce" +
                "ptions to be handled by the debugger\r\ndebugging Meta (e.g. Visual Studio).";
            this.lowLevelDebugMenuItem.Click += new System.EventHandler(this.LowLevel_Click);
            // 
            // forceGCMenuItem
            // 
            this.forceGCMenuItem.MergeIndex = 1;
            this.forceGCMenuItem.Name = "forceGCMenuItem";
            this.forceGCMenuItem.Size = new System.Drawing.Size(158, 22);
            this.forceGCMenuItem.Text = "Force &GC";
            this.forceGCMenuItem.ToolTipText = "Forces an immediate garbage collection.\r\nThis can be useful to close files or oth" +
                "er resources\r\nthat were locked by your program but never\r\nunlocked.";
            this.forceGCMenuItem.Click += new System.EventHandler(this.forceGCMenuItem_Click);
            // 
            // windowsMenu
            // 
            this.windowsMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.zoomMenu,
            this.RecenterMenuItem});
            this.windowsMenu.MergeIndex = 7;
            this.windowsMenu.Name = "windowsMenu";
            this.windowsMenu.Size = new System.Drawing.Size(68, 20);
            this.windowsMenu.Text = "&Windows";
            this.windowsMenu.DropDownOpening += new System.EventHandler(this.windowsMenu_Select);
            // 
            // zoomMenu
            // 
            this.zoomMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.zoom300,
            this.zoom200,
            this.zoom150,
            this.zoom120,
            this.zoom110,
            this.zoom100,
            this.zoom90,
            this.zoom80});
            this.zoomMenu.MergeIndex = 0;
            this.zoomMenu.Name = "zoomMenu";
            this.zoomMenu.Size = new System.Drawing.Size(157, 22);
            this.zoomMenu.Text = "&Zoom";
            this.zoomMenu.ToolTipText = "Changes the magnification on code\r\nNote that this screws up indentation\r\n";
            this.zoomMenu.DropDownOpening += new System.EventHandler(this.zoomMenu_Popup);
            // 
            // zoom300
            // 
            this.zoom300.MergeIndex = 0;
            this.zoom300.Name = "zoom300";
            this.zoom300.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.D3)));
            this.zoom300.Size = new System.Drawing.Size(178, 22);
            this.zoom300.Text = "300%";
            this.zoom300.Click += new System.EventHandler(this.zoom300_Click);
            // 
            // zoom200
            // 
            this.zoom200.MergeIndex = 1;
            this.zoom200.Name = "zoom200";
            this.zoom200.Size = new System.Drawing.Size(178, 22);
            this.zoom200.Text = "200%";
            this.zoom200.Click += new System.EventHandler(this.zoom200_Click);
            // 
            // zoom150
            // 
            this.zoom150.MergeIndex = 2;
            this.zoom150.Name = "zoom150";
            this.zoom150.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.F5)));
            this.zoom150.Size = new System.Drawing.Size(178, 22);
            this.zoom150.Text = "150%";
            this.zoom150.Click += new System.EventHandler(this.zoom150_Click);
            // 
            // zoom120
            // 
            this.zoom120.MergeIndex = 3;
            this.zoom120.Name = "zoom120";
            this.zoom120.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.D2)));
            this.zoom120.Size = new System.Drawing.Size(178, 22);
            this.zoom120.Text = "120%";
            this.zoom120.Click += new System.EventHandler(this.zoom120_Click);
            // 
            // zoom110
            // 
            this.zoom110.MergeIndex = 4;
            this.zoom110.Name = "zoom110";
            this.zoom110.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.D1)));
            this.zoom110.Size = new System.Drawing.Size(178, 22);
            this.zoom110.Text = "110%";
            this.zoom110.Click += new System.EventHandler(this.zoom110_Click);
            // 
            // zoom100
            // 
            this.zoom100.MergeIndex = 5;
            this.zoom100.Name = "zoom100";
            this.zoom100.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.D0)));
            this.zoom100.Size = new System.Drawing.Size(178, 22);
            this.zoom100.Text = "100%";
            this.zoom100.Click += new System.EventHandler(this.zoom100_Click);
            // 
            // zoom90
            // 
            this.zoom90.MergeIndex = 6;
            this.zoom90.Name = "zoom90";
            this.zoom90.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.D9)));
            this.zoom90.Size = new System.Drawing.Size(178, 22);
            this.zoom90.Text = "90%";
            this.zoom90.Click += new System.EventHandler(this.zoom90_Click);
            // 
            // zoom80
            // 
            this.zoom80.MergeIndex = 7;
            this.zoom80.Name = "zoom80";
            this.zoom80.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.D8)));
            this.zoom80.Size = new System.Drawing.Size(178, 22);
            this.zoom80.Text = "80%";
            this.zoom80.Click += new System.EventHandler(this.zoom80_Click);
            // 
            // RecenterMenuItem
            // 
            this.RecenterMenuItem.MergeIndex = 1;
            this.RecenterMenuItem.Name = "RecenterMenuItem";
            this.RecenterMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.L)));
            this.RecenterMenuItem.Size = new System.Drawing.Size(157, 22);
            this.RecenterMenuItem.Text = "&Recenter";
            this.RecenterMenuItem.ToolTipText = "Scrolls the window to place the current line in the middle";
            this.RecenterMenuItem.Click += new System.EventHandler(this.RecenterMenuItem_Click);
            // 
            // GotoMenuItem
            // 
            this.GotoMenuItem.MergeIndex = 8;
            this.GotoMenuItem.Name = "GotoMenuItem";
            this.GotoMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
                        | System.Windows.Forms.Keys.G)));
            this.GotoMenuItem.Size = new System.Drawing.Size(76, 20);
            this.GotoMenuItem.Text = "&Definitions";
            this.GotoMenuItem.ToolTipText = "Use this menu to nagivate directly to the definition of a variable";
            this.GotoMenuItem.DropDownOpening += new System.EventHandler(this.GotoMenuItem_Pop);
            // 
            // HelpMenu
            // 
            this.HelpMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.examplesMenuItem,
            this.searchMenuItem,
            this.helpSeparator1});
            this.HelpMenu.MergeIndex = 9;
            this.HelpMenu.Name = "HelpMenu";
            this.HelpMenu.Size = new System.Drawing.Size(43, 20);
            this.HelpMenu.Text = "&Help";
            // 
            // examplesMenuItem
            // 
            this.examplesMenuItem.MergeIndex = 0;
            this.examplesMenuItem.Name = "examplesMenuItem";
            this.examplesMenuItem.Size = new System.Drawing.Size(133, 22);
            this.examplesMenuItem.Text = "Examples ...";
            this.examplesMenuItem.ToolTipText = "View examine Meta code";
            this.examplesMenuItem.Click += new System.EventHandler(this.examplesMenuItem_Click);
            // 
            // searchMenuItem
            // 
            this.searchMenuItem.MergeIndex = 1;
            this.searchMenuItem.Name = "searchMenuItem";
            this.searchMenuItem.Size = new System.Drawing.Size(133, 22);
            this.searchMenuItem.Text = "Search ...";
            this.searchMenuItem.ToolTipText = "Search for variables whose names or\r\ndocumentation include a given keyword";
            this.searchMenuItem.Click += new System.EventHandler(this.AproposClick);
            // 
            // helpSeparator1
            // 
            this.helpSeparator1.MergeIndex = 2;
            this.helpSeparator1.Name = "helpSeparator1";
            this.helpSeparator1.Size = new System.Drawing.Size(130, 6);
            // 
            // CheckMenu
            // 
            this.CheckMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.CheckMenuItem,
            this.AutoCheckMenuItem});
            this.CheckMenu.MergeIndex = 10;
            this.CheckMenu.Name = "CheckMenu";
            this.CheckMenu.Size = new System.Drawing.Size(50, 20);
            this.CheckMenu.Text = "&Check";
            this.CheckMenu.DropDownOpening += new System.EventHandler(this.CheckMenu_Popup);
            // 
            // CheckMenuItem
            // 
            this.CheckMenuItem.MergeIndex = 0;
            this.CheckMenuItem.Name = "CheckMenuItem";
            this.CheckMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F1)));
            this.CheckMenuItem.Size = new System.Drawing.Size(176, 22);
            this.CheckMenuItem.Text = "&Check now";
            this.CheckMenuItem.Click += new System.EventHandler(this.CheckMenuItem_Click);
            // 
            // AutoCheckMenuItem
            // 
            this.AutoCheckMenuItem.MergeIndex = 1;
            this.AutoCheckMenuItem.Name = "AutoCheckMenuItem";
            this.AutoCheckMenuItem.Size = new System.Drawing.Size(176, 22);
            this.AutoCheckMenuItem.Text = "Auto check";
            this.AutoCheckMenuItem.Click += new System.EventHandler(this.AutoCheckMenuItem_Click);
            // 
            // statusBar
            // 
            this.statusBar.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.statusBar.Dock = System.Windows.Forms.DockStyle.None;
            this.statusBar.Font = new System.Drawing.Font("Arial Unicode MS", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.statusBar.Location = new System.Drawing.Point(0, 267);
            this.statusBar.Name = "statusBar";
            this.statusBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
            this.valuePanel,
            this.arglistPanel});
            this.statusBar.ShowPanels = true;
            this.statusBar.Size = new System.Drawing.Size(552, 20);
            this.statusBar.TabIndex = 0;
            this.statusBar.Text = "statusBar";
            // 
            // valuePanel
            // 
            this.valuePanel.MinWidth = 100;
            this.valuePanel.Name = "valuePanel";
            this.valuePanel.Width = 150;
            // 
            // arglistPanel
            // 
            this.arglistPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
            this.arglistPanel.MinWidth = 200;
            this.arglistPanel.Name = "arglistPanel";
            this.arglistPanel.Width = 385;
            // 
            // contextMenu
            // 
            this.contextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.contextCut,
            this.contextCopy,
            this.contextPaste,
            this.contextSeparator1,
            this.contextExecute,
            this.contextSingleStep,
            this.contextInspect,
            this.contextContinueExecutionMenuItem,
            this.contextSeparator2,
            this.contextTrace,
            this.contextBreakpoint,
            this.contextBreakpointExpressionMenuItem,
            this.menuItem7,
            this.traceAnalysisMenuItem,
            this.contextSeparator3,
            this.contextFindDefinition,
            this.contextFindUsesMenuItem});
            this.contextMenu.Name = "contextMenu";
            this.contextMenu.Size = new System.Drawing.Size(218, 314);
            this.contextMenu.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenu1_Popup);
            // 
            // contextCut
            // 
            this.contextCut.MergeIndex = 0;
            this.contextCut.Name = "contextCut";
            this.contextCut.Size = new System.Drawing.Size(217, 22);
            this.contextCut.Text = "Cut";
            this.contextCut.Click += new System.EventHandler(this.Cut_Click);
            // 
            // contextCopy
            // 
            this.contextCopy.MergeIndex = 1;
            this.contextCopy.Name = "contextCopy";
            this.contextCopy.Size = new System.Drawing.Size(217, 22);
            this.contextCopy.Text = "Copy";
            this.contextCopy.Click += new System.EventHandler(this.Copy_Click);
            // 
            // contextPaste
            // 
            this.contextPaste.MergeIndex = 2;
            this.contextPaste.Name = "contextPaste";
            this.contextPaste.Size = new System.Drawing.Size(217, 22);
            this.contextPaste.Text = "Paste";
            this.contextPaste.Click += new System.EventHandler(this.Paste_Click);
            // 
            // contextSeparator1
            // 
            this.contextSeparator1.MergeIndex = 3;
            this.contextSeparator1.Name = "contextSeparator1";
            this.contextSeparator1.Size = new System.Drawing.Size(214, 6);
            // 
            // contextExecute
            // 
            this.contextExecute.MergeIndex = 4;
            this.contextExecute.Name = "contextExecute";
            this.contextExecute.Size = new System.Drawing.Size(217, 22);
            this.contextExecute.Text = "Execute";
            this.contextExecute.Click += new System.EventHandler(this.Evaluate_Click);
            // 
            // contextSingleStep
            // 
            this.contextSingleStep.MergeIndex = 5;
            this.contextSingleStep.Name = "contextSingleStep";
            this.contextSingleStep.Size = new System.Drawing.Size(217, 22);
            this.contextSingleStep.Text = "Execute 1 step";
            this.contextSingleStep.Click += new System.EventHandler(this.SingleStep_Click);
            // 
            // contextInspect
            // 
            this.contextInspect.MergeIndex = 6;
            this.contextInspect.Name = "contextInspect";
            this.contextInspect.Size = new System.Drawing.Size(217, 22);
            this.contextInspect.Text = "Execute and inspect";
            this.contextInspect.Click += new System.EventHandler(this.Inspect_Click);
            // 
            // contextContinueExecutionMenuItem
            // 
            this.contextContinueExecutionMenuItem.MergeIndex = 7;
            this.contextContinueExecutionMenuItem.Name = "contextContinueExecutionMenuItem";
            this.contextContinueExecutionMenuItem.Size = new System.Drawing.Size(217, 22);
            this.contextContinueExecutionMenuItem.Text = "Continue execution to here";
            this.contextContinueExecutionMenuItem.Click += new System.EventHandler(this.continueExecutionMenuItem_Click);
            // 
            // contextSeparator2
            // 
            this.contextSeparator2.MergeIndex = 8;
            this.contextSeparator2.Name = "contextSeparator2";
            this.contextSeparator2.Size = new System.Drawing.Size(214, 6);
            // 
            // contextTrace
            // 
            this.contextTrace.MergeIndex = 9;
            this.contextTrace.Name = "contextTrace";
            this.contextTrace.Size = new System.Drawing.Size(217, 22);
            this.contextTrace.Text = "Trace Procedure";
            this.contextTrace.Click += new System.EventHandler(this.Trace_Click);
            // 
            // contextBreakpoint
            // 
            this.contextBreakpoint.MergeIndex = 10;
            this.contextBreakpoint.Name = "contextBreakpoint";
            this.contextBreakpoint.Size = new System.Drawing.Size(217, 22);
            this.contextBreakpoint.Text = "Breakpoint Procedure";
            this.contextBreakpoint.Click += new System.EventHandler(this.Breakpoint_Click);
            // 
            // contextBreakpointExpressionMenuItem
            // 
            this.contextBreakpointExpressionMenuItem.MergeIndex = 11;
            this.contextBreakpointExpressionMenuItem.Name = "contextBreakpointExpressionMenuItem";
            this.contextBreakpointExpressionMenuItem.Size = new System.Drawing.Size(217, 22);
            this.contextBreakpointExpressionMenuItem.Text = "Breakpoint Expression";
            this.contextBreakpointExpressionMenuItem.Click += new System.EventHandler(this.breakpointExpressionMenuItem_Click);
            // 
            // menuItem7
            // 
            this.menuItem7.MergeIndex = 12;
            this.menuItem7.Name = "menuItem7";
            this.menuItem7.Size = new System.Drawing.Size(214, 6);
            // 
            // traceAnalysisMenuItem
            // 
            this.traceAnalysisMenuItem.MergeIndex = 13;
            this.traceAnalysisMenuItem.Name = "traceAnalysisMenuItem";
            this.traceAnalysisMenuItem.Size = new System.Drawing.Size(217, 22);
            this.traceAnalysisMenuItem.Text = "Trace analysis";
            this.traceAnalysisMenuItem.Click += new System.EventHandler(this.traceAnalysisMenuItem_Click);
            // 
            // contextSeparator3
            // 
            this.contextSeparator3.MergeIndex = 14;
            this.contextSeparator3.Name = "contextSeparator3";
            this.contextSeparator3.Size = new System.Drawing.Size(214, 6);
            // 
            // contextFindDefinition
            // 
            this.contextFindDefinition.MergeIndex = 15;
            this.contextFindDefinition.Name = "contextFindDefinition";
            this.contextFindDefinition.Size = new System.Drawing.Size(217, 22);
            this.contextFindDefinition.Text = "Find definition";
            this.contextFindDefinition.Click += new System.EventHandler(this.FindDefinition_Click);
            // 
            // contextFindUsesMenuItem
            // 
            this.contextFindUsesMenuItem.MergeIndex = 16;
            this.contextFindUsesMenuItem.Name = "contextFindUsesMenuItem";
            this.contextFindUsesMenuItem.Size = new System.Drawing.Size(217, 22);
            this.contextFindUsesMenuItem.Text = "Find uses";
            this.contextFindUsesMenuItem.Click += new System.EventHandler(this.contextFindUsesMenuItem_Click);
            // 
            // Editor
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
            this.BackColor = System.Drawing.SystemColors.Control;
            this.ClientSize = new System.Drawing.Size(600, 400);
            this.Controls.Add(this.mainMenu);
            this.Controls.Add(this.statusBar);
            this.Font = new System.Drawing.Font("Arial Unicode MS", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MainMenuStrip = this.mainMenu;
            this.Name = "Editor";
            this.Text = "Untitled";
            this.mainMenu.ResumeLayout(false);
            this.mainMenu.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.valuePanel)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.arglistPanel)).EndInit();
            this.contextMenu.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		protected override void OnLayout(LayoutEventArgs e) {
            mainMenu.Width = ClientSize.Width;
            code.Top = mainMenu.Bottom;
			code.Size = new Size(ClientSize.Width, ClientSize.Height-statusBar.Size.Height-mainMenu.Height);
			statusBar.Bounds = new Rectangle(0, ClientSize.Height-statusBar.Height, ClientSize.Width, statusBar.Height);
		}

        protected override void OnLocationChanged(EventArgs e)
        {
            Rectangle max = MaximizedBounds;
            max.X = Left;
            MaximizedBounds = max;
            base.OnLocationChanged(e);
        }

        protected override void OnVisibleChanged(EventArgs e)
        {
            if (Visible)
            {
                Rectangle max = MaximizedBounds;
                max.X = Left;
                MaximizedBounds = max;
            }
            base.OnVisibleChanged(e);
        }

		protected override void OnBackColorChanged(EventArgs e) {
			code.BackColor = BackColor;
			base.OnBackColorChanged(e);
		}

        delegate void IHateThis3(string x);

        public void SetValueText(string text)
        {
            if (this.InvokeRequired)
                Invoke(new IHateThis3(SetValueTextInternal), new object[1] { text });
            else SetValueTextInternal(Text);
        }

		public void SetValueTextInternal(string text) {
			this.valuePanel.Text = text;
		}

        public void SetArglistText(string text)
        {
            if (InvokeRequired)
                Invoke(new IHateThis3(SetArglistTextInternal), new object[] { text });
            else SetArglistTextInternal(text);
        }

		public void SetArglistTextInternal(string text) {
			arglistTimer.Stop();
			arglistPanel.Text = text==null?"":text;
		}

		private void FileNew_Click(object sender, System.EventArgs e) {
			new Editor().Show();
		}

		private void FileSaveAs_Click(object sender, System.EventArgs e) {
			SaveAs();
		}

		private void FileOpen_Click(object sender, System.EventArgs e) {
			Stream myStream;
			OpenFileDialog openFileDialog1 = new OpenFileDialog();
			if (saveFileName!=null)
				openFileDialog1.InitialDirectory = Path.GetDirectoryName(saveFileName);

			//openFileDialog1.InitialDirectory = "c:\\" ;
			openFileDialog1.Filter = "Source files (*.meta;*.mscript)|*.meta;*.mscript|Scheme files (*.scm)|*.scm|Dump files (*.mdump)|*.mdump|All files (*.*)|*.*" ;
			openFileDialog1.FilterIndex = 1 ;
			openFileDialog1.RestoreDirectory = true ;

			if(openFileDialog1.ShowDialog() == DialogResult.OK) {
				if((myStream = openFileDialog1.OpenFile())!= null) {
					// Insert code to read the stream here.
					myStream.Close();
					if (Path.GetExtension(openFileDialog1.FileName)==".mdump") {
						LoadDumpFile(openFileDialog1.FileName);
					} else {
						Editor ed = FindEditor(FileToken.GetToken(openFileDialog1.FileName));
						if (ed.WindowState==FormWindowState.Minimized)
							ed.WindowState = FormWindowState.Normal;
						ed.BringToFront();
						//new Editor(openFileDialog1.FileName).Show();
					}
				}
			}
			openFileDialog1.Dispose();
		}

		public static void LoadDumpFile(string filename) {
			try {
				IFormatter formatter = new BinaryFormatter();
				Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
				Inspector.Inspect(formatter.Deserialize(stream));
				stream.Close();
			} catch (Exception ex) {
				MessageBox.Show(ex.Message, "Error reading dump file");
				Inspector.Inspect(ex);
			}
		}

		private void HandleModified(object sender, EventArgs e) {
			if (!(this is Listener) && !reallyModified)
				Text = Name+" *";
			reallyModified = true;
            regenerateGotoMenu = true;
		}

		void ClearModified() {
			reallyModified = false;
			code.Modified = false;
			Text = Name;
		}

		private void HandleQuit(object sender, EventArgs e) {
			HandleClose(null, null);
		}

		private void HandleClose(object sender, CancelEventArgs e) {
			if (this==Listener.mainListener) {
				if (MessageBox.Show("Closing this window will exit Meta.  Do you wish to close?", "Exit", MessageBoxButtons.YesNo) == DialogResult.Yes) {
					if (CloseAllEditorWindows())
						e.Cancel|= true;
					else
						System.Environment.Exit(0);
				} else
					e.Cancel=true;
			} else {
				if (reallyModified) {
					switch (MessageBox.Show("Save file "+Name+"?", Name, MessageBoxButtons.YesNoCancel)) {
						case DialogResult.Yes:
							Save();
							break;

						case DialogResult.No:
							break;

						case DialogResult.Cancel:
							e.Cancel = true;
							break;
					}
				}
				if (!e.Cancel)
					RemoveFromEditorTable();
			}
		}

		void SaveAs() {
			SaveFileDialog saveFileDialog1 = new SaveFileDialog();
			if (saveFileName!=null)
				saveFileDialog1.InitialDirectory = Path.GetDirectoryName(saveFileName);
 
			//saveFileDialog1.Filter = "Code files (*.meta)|*.meta|All files (*.*)|*.*";
			saveFileDialog1.Filter = "Source files (*.meta)|*.meta|Autorun scripts (*.mscript)|*.mscript|All files (*.*)|*.*";
			saveFileDialog1.FilterIndex = 1 ;
			saveFileDialog1.RestoreDirectory = true ;
 
			if(saveFileDialog1.ShowDialog() == DialogResult.OK) {
				try {
					code.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
					FileName = saveFileDialog1.FileName;
					Name = Path.GetFileName(FileName);
#if oldickysavefile
					Stream myStream ;
					if((myStream = saveFileDialog1.OpenFile()) != null) {
						FileName = saveFileDialog1.FileName;
						StreamWriter myStreamWriter = new StreamWriter(myStream);

						if (myStreamWriter != null) {				
							// Loop through the array and send the contents of the array to debug window.
							/*for(int counter=0; counter < code.Lines.Length; counter++)
							{
								myStreamWriter.Write(code.Lines[counter]);
								myStreamWriter.Write('\n');
							}*/
							myStreamWriter.Write(code.Rtf);

							myStreamWriter.Close();
						}

						myStream.Close();
				}
#endif
					ClearModified();
				} catch {
					MessageBox.Show("Couldn't save file "+saveFileName, "Problem saving file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					SaveAs();
				}
			}
			saveFileDialog1.Dispose();
		}

		static string tempDir = Path.Combine(Path.GetDirectoryName(System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory)),
			"Temp");
		bool IsTempFile(string path) {
			return false;
			//return path.StartsWith(tempDir);
		}

		public void Save() {
			code.NoteUserSelection();  // Needed for MarkUndo() in FinishReindentBeforeSave().
			code.FinishReindentBeforeSave();
			if (saveFileName == null)
				SaveAs();
			else if (IsTempFile(tempDir) && MessageBox.Show("This file appears to come from a temporary file directory that is not easily accessible.  This can occur if you open the file as a link in a browser or as an email attachment.  If you save the file here, it may be difficult to recover.  Would you like to save it to a different location?",
				"Saving temporary file", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)==DialogResult.Yes)
				SaveAs();
			else {
				try {
					// Some students have reported problems with files being truncated to zero length,
					// presumably because an error gets thrown saving the file but the OS has already
					// truncated it.  So we save in paranoid mode.
					string tempfile = this.FileName + ".new";
					code.SaveFile(tempfile, RichTextBoxStreamType.RichText);
					FileInfo i = new FileInfo(tempfile);
					if (i.Length>0) {
						if (System.IO.File.Exists(this.FileName))
							System.IO.File.Delete(this.FileName);
						i.MoveTo(this.FileName);
					}
#if oldickysavefile
					StreamWriter myStream = new StreamWriter(saveFileName,false);

					if (myStream != null) {				
						// Loop through the array and send the contents of the array to debug window.
						/*for(int counter=0; counter <= code.Lines.Length; counter++)
							{
								myStream.Write(code.Lines[counter]);
								myStream.Write('\n');
							}*/

						myStream.Write(code.Rtf);
						myStream.Close();
					}
#endif
					ClearModified();
				} catch {
					MessageBox.Show("Couldn't save file "+saveFileName, "Problem saving file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					SaveAs();
				}
			}
		}

		private void FileSave_Click(object sender, System.EventArgs e) {
			Save();
		}

		private void FileClose_Click(object sender, System.EventArgs e) {
			Close();
		}

		public Expression ExpressionAt(int filelocation) {
			string definitionName = code.DefinitionNameAt(filelocation);
			Meta.Procedure fbinding = Namespace.CheckFbinding(definitionName);
			int start = code.StartOfDefinitionAt(filelocation);
			if (start>=0 && fbinding!=null)
				return ExpressionAtOffset(fbinding, filelocation-start);
			else
				return null;
		}

		LocalVariable FindLocalOfLambda(LambdaExpression l, string name) {
			foreach (LocalVariable v in l.argumentVariables) {
				if (v.name.name==name)
					return v;
			}
			return null;
		}

		Variable FindBinding(Expression e, string name) {
			while (e!=null) {
				if (e is LambdaExpression) {
					LocalVariable v = FindLocalOfLambda((LambdaExpression)e, name);
					if (v!=null)
						return v;
				} else if (e is Application) {
					Application a = (Application)e;
					if (a.function is LambdaExpression) {
						LocalVariable v = FindLocalOfLambda((LambdaExpression)a.function, name);
						if (v!=null)
							return v;
					}
				}
				e = e.enclosingExpression;
			}
			return Namespace.Lookup(Symbol.Intern(name), true, false, true);
		}

		public Expression ExpressionAtIncludingVariable(int filelocation) {
			CodeScanner sc = code.ScanCharsFrom(filelocation);
			if (Char.GetUnicodeCategory(sc.CurrentChar)==System.Globalization.UnicodeCategory.OpenPunctuation)
				// We're looking at a normal expression
				return ExpressionAt(filelocation);
			// We think we're looking at a variable reference.
			int start=sc.SkipBackwardToken();
			if (start>=0 && sc.CurrentChar!='[' && sc.CurrentChar!='(') {
				int end=sc.SkipForwardToken();
				if (end<code.TextLength) {
					string maybeVar=code.RegionText(new Region(start, end-start));
					int dot=maybeVar.IndexOf('.');
					if (dot>=0)
						maybeVar = maybeVar.Substring(0,dot);
					sc.MaybeSkipBackwardToEnclosingExpression();
					if (!sc.AtBeginningOfBuffer) {
						Expression enclosing = ExpressionAt(sc.charIndex);
						return FindBinding(enclosing, maybeVar);
					}
				}
			}
			return null;
		}

		internal Expression ExpressionAt(Procedure p, int filelocation) {
			int start = code.StartOfDefinitionAt(filelocation);
			if (start>=0)
				return ExpressionAtOffset(p, filelocation-start);
			else
				return null;
		}

		internal Expression ExpressionAtOffset(Procedure p, int offset) {
			if (Utilities.IsRemote(p))
				return null;
			InterpretedProcedureBase i = p as InterpretedProcedureBase;
			GenericProcedure g = p as GenericProcedure;
//			CodeScanner sc=code.ScanCharsFrom(filelocation);
//			if (Char.GetUnicodeCategory(sc.CurrentChar)!=System.Globalization.UnicodeCategory.OpenPunctuation) {
//				sc.SkipBackwardToEnclosingExpression();
//				filelocation = sc.charIndex;
//			}
			if (i!=null)
				return ExpressionAtOffset(i.sourceExpression, offset);
			else if (g!=null) {
				foreach (GenericProcedure.Method m in g.methodList) {
					InterpretedProcedureBase impl = m.implementation as InterpretedProcedureBase;
					if (impl!=null) {
						Expression e = ExpressionAtOffset(impl.sourceExpression, offset);
						if (e!=null)
							return e;
					}
				}
				return null;
			} else
				return null;
		}

		Expression ExpressionAtOffset(Expression e, int offset) {
			if (e==null)
				return null;

			if (e.SourceOffset==offset)
				return e;
			else
				foreach (Expression s in (IList)(e.Subexpressions)) {
					Expression result = ExpressionAtOffset(s, offset);
					if (result!=null)
						return result;
				}
			return null;
		}


#if ABSOLUTE_FILE_LOCATIONS
		internal Expression ExpressionAt(Procedure p, int filelocation) {
			if (Utilities.IsRemote(p))
				return null;
			InterpretedProcedureBase i = p as InterpretedProcedureBase;
			GenericProcedure g = p as GenericProcedure;
			CodeScanner sc=code.ScanCharsFrom(filelocation);
			if (Char.GetUnicodeCategory(sc.CurrentChar)!=System.Globalization.UnicodeCategory.OpenPunctuation) {
				sc.SkipBackwardToEnclosingExpression();
				filelocation = sc.charIndex;
			}
			if (i!=null)
				return ExpressionAt(i.sourceExpression, filelocation);
			else if (g!=null) {
				foreach (GenericProcedure.Method m in g.methodList) {
					InterpretedProcedureBase impl = m.implementation as InterpretedProcedureBase;
					if (impl!=null) {
						Expression e = ExpressionAt(impl.sourceExpression, filelocation);
						if (e!=null)
							return e;
					}
				}
				return null;
			} else
				return null;
		}
#endif

		Expression ExpressionAt(Expression e, int filelocation) {
			if (e==null)
				return null;

			if (e.sourceLocation==filelocation)
				return e;
			else
				foreach (Expression s in (IList)(e.Subexpressions)) {
					Expression result = ExpressionAt(s, filelocation);
					if (result!=null)
						return result;
				}
			return null;
		}

		private void MenuPop_Execute(object sender, System.EventArgs e) {
			bool running = (Listener.mainListener.evalThread != null && Listener.mainListener.evalThread.IsAlive);
			bool breakpointed = Meta.TopLevel.ThreadBeingDebugged!=null;

			code.NoteUserSelection();
			Evaluate.Enabled = !running || breakpointed;
			SingleStepMenuItem.Enabled = !running || breakpointed;
			Evaluate.Text = breakpointed?"Continue execution":"Execute";
			inspectMenuItem.Enabled = !running;
			executeSelectionMenuItem.Enabled = !running;
			executeAllMenuItem.Enabled = !running && !(this is Listener);
			loadMenuItem.Enabled = !running;

			string definitionName = code.CurrentDefinitionVariable;
			Meta.Procedure fbinding = this.Namespace.CheckFbinding(definitionName);

			breakpointMenuItem.Enabled = fbinding!= null;
			breakpointMenuItem.Checked = fbinding!=null && fbinding.Breakpointed;
			traceMenuItem.Enabled = fbinding!=null;
			traceMenuItem.Checked = fbinding!=null && fbinding.Traced;

			Expression exp = fbinding!=null?ExpressionAt(fbinding, code.UserSelection.start):null;
			breakpointExpressionMenuItem.Enabled = exp!=null;
			breakpointExpressionMenuItem.Checked = exp!=null && exp.executionMode.Breakpoint;
			continueExecutionMenuItem.Enabled = breakpointExpressionMenuItem.Enabled && breakpointed;

			StopExec.Enabled = running;
			InterruptExecution.Enabled = running && !breakpointed;
			clearAllBreakpointsMenuItem.Enabled = Meta.TopLevel.BreakpointsSet;
			clearAllTracesMenuItem.Enabled = Meta.TopLevel.TracesSet;
			traceLoadMenuItem.Checked = Meta.TopLevel.TraceLoading;
			code.RestoreUserSelection();
			code.UnlockWindowDammit();
		}

		private void MenuPop_Advanced(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			lowLevelDebugMenuItem.Checked = Meta.TopLevel.lowLevelDebug;
			showDetailMenuItem.Checked = Inspector.showDetail;
			beginnerModeMenuItem.Checked = EvalStack.showAllExpressions
				&& Expression.OptimizeTailCalls.DefaultValue is bool && (bool)Expression.OptimizeTailCalls.DefaultValue==false
				&& Inspector.showDetail==false && Meta.TopLevel.AlwaysOpen2D;
			code.RestoreUserSelection();
			code.UnlockWindowDammit();
		}

		private void Breakpoint_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			string varName = code.CurrentDefinitionVariable;
			object binding = this.Namespace.CheckBinding(varName);

			if (varName==null || varName=="")
				MessageBox.Show("The cursor isn't in a definition.", "Sorry, can't set breakpoint", MessageBoxButtons.OK);
			else if (binding==null)
				MessageBox.Show(varName + " isn't defined yet.", "Sorry, can't set breakpoint", MessageBoxButtons.OK);
			else if (binding is Meta.Procedure) {
				Meta.Procedure proc = (Meta.Procedure)binding;
				Meta.TopLevel.ToggleBreakpoint(proc);
				//proc.breakpoint = !proc.breakpoint;
				UpdateVariableValue();
			} else
				MessageBox.Show(varName + " isn't a function.", "Sorry, can't set breakpoint", MessageBoxButtons.OK);
				
			code.RestoreUserSelection();
		}

		private void Trace_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			string varName = code.CurrentDefinitionVariable;
			object binding = this.Namespace.CheckBinding(varName);

			if (varName==null || varName=="")
				MessageBox.Show("The cursor isn't in a definition.", "Sorry, can't set tracing", MessageBoxButtons.OK);
			else if (binding==null)
				MessageBox.Show(varName + " isn't defined yet.", "Sorry, can't set tracing", MessageBoxButtons.OK);
			else if (binding is Meta.Procedure) {
				Meta.Procedure proc = (Meta.Procedure)binding;
				Meta.TopLevel.ToggleTrace(proc);
				//proc.breakpoint = !proc.breakpoint;
				UpdateVariableValue();
			} else
				MessageBox.Show(varName + " isn't a function.", "Sorry, can't set tracing", MessageBoxButtons.OK);
				
			code.RestoreUserSelection();
		}

		private void LowLevel_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.lowLevelDebug = !Meta.TopLevel.lowLevelDebug;
			lowLevelDebugMenuItem.Checked = Meta.TopLevel.lowLevelDebug;
		}

		private void SpeedUpEditor_Click(object sender, System.EventArgs e) {
			fastMode = !fastMode;
			speedUpEditorMenuItem.Checked = fastMode;
		}

		private void ShowDetail_Click(object sender, System.EventArgs e) {
			Inspector.showDetail = !Inspector.showDetail;
			showDetailMenuItem.Checked = Inspector.showDetail;
		}
		
		private void StopExec_Click(object sender, System.EventArgs e) {
			code.HandleStop(sender, e);
		}

		private void SelectAll_Click(object sender, System.EventArgs e) {
			code.HandleSelectAll(sender, e);
		}

		private void Cut_Click(object sender, System.EventArgs e) {
			code.HandleCut(sender, e);
		}

		private void Copy_Click(object sender, System.EventArgs e) {
			code.HandleCopy(sender, e);
		}

		private void Paste_Click(object sender, System.EventArgs e) {
			code.HandlePaste(sender, e);
		}

		private void Transpose_Click(object sender, EventArgs e) {
			code.HandleTranspose(sender, e);
		}

		private void Font_Click(object sender, System.EventArgs e) {
			code.HandleFont(sender, e);
		}

		private void Evaluate_Click(object sender, System.EventArgs e) {
			if (Meta.TopLevel.ThreadBeingDebugged!=null) {
				Meta.TopLevel.ThreadBeingDebugged.Continue();
				CodeBox.SuppressKeyUp(Keys.E);
			} else {
				Meta.TopLevel.CurrentSourceFileToken = fileToken;
				code.HandleEval(sender, e);
			}
		}

		private void SingleStep_Click(object sender, System.EventArgs e) {
			if (Meta.TopLevel.ThreadBeingDebugged != null) {
				Meta.TopLevel.ThreadBeingDebugged.Step();
			} else {
				Meta.TopLevel.CurrentSourceFileToken = fileToken;
				code.HandleStep(sender, e);
			}
			CodeBox.SuppressKeyUp(Keys.D1);
		}

		private void Inspect_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.CurrentSourceFileToken = fileToken;
			code.HandleInspect(sender, e);
		}

		private void EditMenu_Pop(object sender, EventArgs ea) {
			code.NoteUserSelection();
			Expression e = Expression.FindableExpression(code.CurrentVariableExpression);

			undoMenuItem.Enabled = code.undoEnabled;
			FindDefinitionMenuItem.Enabled = e!=null;
			FindDefinitionMenuItem.Text = (e==null)?"Find &Definition":("Find &Definition of "+e.definedIn);
			string var = code.CurrentDefinitionVariable;
			ShowReferencesMenuItem.Enabled = var!=null && var!="";
			ShowReferencesMenuItem.Text = ShowReferencesMenuItem.Enabled?("Show &references to "+var):"Show &references";
			var = code.CurrentVariableName;
			ShowReferencesMenuItem2.Enabled = var!=null && var!="";
			ShowReferencesMenuItem2.Text = ShowReferencesMenuItem2.Enabled?("Show &references to "+var):"Show &references";
			code.UnlockWindowDammit();
		}

		private void FindDefinition_Click(object sender, EventArgs ea) {
			EditSource(code.CurrentVariableExpression, false, true);
		}

		private void LangSpec_Click(object sender, System.EventArgs e) {
			new HelpBrowser("Manual.htm").Show();
		}

		private void FileExit_Click(object sender, System.EventArgs e) {
			Meta.Editor.Listener.mainListener.Close();
		}

		private void About_Click(object sender, System.EventArgs e) {
			AboutDialog aboutdlg = new AboutDialog();
			aboutdlg.ShowDialog();
		}

#if SYNTAXHIGHLIGHTING
		private void Pref_Click(object sender, System.EventArgs e)
		{
			Options options = new Options(code);
			options.Show();
		}
#endif

		private void PrinterSettingsMenu_Click(object sender, System.EventArgs e) {
			this.printDialog1.Document = this.ThePrintDocument;
			printDialog1.ShowDialog();
		}

		private void PreviewMenu_Click(object sender, System.EventArgs e) {
			try {
				// read string from editor window
				string strText = this.code.Text;
				myReader = new StringReader(strText);
				
				// instantiate new print preview dialog
				PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
				printPreviewDialog1.Document = this.ThePrintDocument;

				// Show the print preview dialog, uses print page event to draw preview screen
				printPreviewDialog1.ShowDialog();
			}
			catch(Exception exp) {
				MessageBox.Show("Printing Error: " + exp.Message + "\n" + exp.Source + "\n" + exp.TargetSite);
			}
		}

		private void FilePrint_Click(object sender, System.EventArgs e) {
			printDialog1.Document = ThePrintDocument;
			string strText = this.code.Text;
			myReader = new StringReader(strText);
			if (printDialog1.ShowDialog() == DialogResult.OK) {
				try {
					this.ThePrintDocument.Print();
				}
				catch (Exception ex) {
					MessageBox.Show("Error: " + ex.Message);
				}
			}
		}

		protected void ThePrintDocument_PrintPage (object sender, System.Drawing.Printing.PrintPageEventArgs ev) {
			float linesPerPage = 0;
			float yPosition = 0;
			int count = 0;
			float leftMargin = ev.MarginBounds.Left;
			float topMargin = ev.MarginBounds.Top; 
			string line = null;
			Font printFont = this.code.Font;
			SolidBrush myBrush = new SolidBrush(Color.Black);

			// Work out the number of lines per page, using the MarginBounds. 

			linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);

			// Iterate over the string using the StringReader, printing each line. 

			while(count < linesPerPage && ((line=myReader.ReadLine()) != null)) {

				// calculate the next line position based on
				// the height of the font according to the printing device 

				yPosition = topMargin + (count * printFont.GetHeight(ev.Graphics));

				// draw the next line in the rich edit control 

				ev.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());

				count++;
			}

			// If there are more lines, print another page. 

			if  (line != null)
				ev.HasMorePages = true;
			else
				ev.HasMorePages = false;

			myBrush.Dispose();
		}

#if SYNTAXHIGLIGHTING
		// Handle a user clicking on the "Syntax Highlighting" Menu.
		private void HighLightMenu_Click(object sender, System.EventArgs e) {
			if (EditorConfiguration.canHighlight) {
				HighLightMenu.Checked = EditorConfiguration.doComment = !HighLightMenu.Checked;
				if (HighLightMenu.Checked)
					code.SyntaxHighlight();
				else
					code.SyntaxUnhighlight();
			}
		}
#endif

		private void EvalFile_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.CurrentSourceFileToken = FileToken.GetToken(saveFileName);
			code.HandleEvalFile(sender, e);
		}

		private void EvalRegion_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.CurrentSourceFileToken = FileToken.GetToken(saveFileName);
			code.HandleEvalRegion(sender, e);
		}

		private void CntxtSelAll_Click(object sender, System.EventArgs e) {
			code.HandleSelectAll(sender, e);
		}

		private void CntxtCut_Click(object sender, System.EventArgs e) {
			code.HandleCut(sender, e);
		}

		private void CntxtCopy_Click(object sender, System.EventArgs e) {
			code.HandleCopy(sender, e);
		}

		private void CntxtPste_Click(object sender, System.EventArgs e) {
			code.HandlePaste(sender, e);
		}

		private void Undo_Click(object sender, System.EventArgs e) {
			code.HandleUndo(sender, e);
		}

		void FormatMenuPop(object sender, EventArgs e) {
			code.FormatMenuPop(formatBold, formatItalic, formatBullet);
		}

		void FormatBoldClick(object sender, EventArgs e) {
			code.FormatBoldClick(sender,e);
		}
		void FormatItalicClick(object sender, EventArgs e) {
			code.FormatItalicClick(sender,e);
		}
		void FormatGrowClick(object sender, EventArgs e) {
			code.FormatGrowClick(sender,e);
		}
		void FormatShrinkClick(object sender, EventArgs e) {
			code.FormatShrinkClick(sender,e);
		}
		void FormatSuperscriptClick(object sender, EventArgs e) {
			code.FormatSuperscriptClick(sender,e);
		}
		void FormatSubscriptClick(object sender, EventArgs e) {
			code.FormatSubscriptClick(sender,e);
		}
		void FormatBulletClick(object sender, EventArgs e) {
			code.FormatBulletClick(sender, e);
		}


		void MaybeShowArglist(object sender, EventArgs e) {
			if (code.WindowLocked)
				return;
			arglistTimer.Stop();
			if (!fastMode && !code.iSearchMode)
				MaybeShowArglist();
		}

		void MaybeShowArglist() {
			arglistOperator = code.CurrentExpressionOperator;
			SetArglistText(GetArglist(arglistOperator));
			arglistTimer.Start();
		}

		void ShowDocumentation(object sender, EventArgs e) {
			if (arglistOperator != null) {
				string docs = Utilities.Documentation(this.Namespace.CheckBinding(arglistOperator));
				if (docs!=null)
					SetArglistText(docs);
			}
		}

		string GetArglist(string variableName) {
			if (variableName==null)
				return null;
			int point = variableName.LastIndexOf('.');
			if (point>0) {
				MemberInfo[] methods = ResolveCSName(variableName) as MemberInfo[];
				if (methods==null || methods.Length==0)
					return null;
					//					else if (methods.Length>1)
					//						return "Arguments vary";
				else if (!(methods[0] is MethodInfo))
					return null;
				else
					return FormatMethodArgInfo(variableName, (MethodInfo)methods[0])+((methods.Length>1)?(" + "+methods.Length.ToString()+" overloads"):"");
			} else {
				object op = this.Namespace.CheckBinding(variableName);
				object[] arglist=Utilities.Arglist(op);
	
				if (arglist != null) {
					string[] prototype = new string[2*arglist.Length+ 3];

					prototype[0] = "[";
					prototype[1] = variableName;
					prototype[2] = " ";
					for (int i=0; i< arglist.Length; i++) {
						prototype[2*i+3] = (arglist[i] is string)?(string)arglist[i]:((Meta.Symbol)arglist[i]).name;
						prototype[2*i+4] = " ";
					}
					prototype[prototype.Length-1] = "]";
					return string.Concat(prototype);
				} else
					return null;
			}
		}

		object ResolveCSName(string csName) {
			int point = csName.LastIndexOf('.');
			if (point<0)
				return this.Namespace.CheckBinding(csName);
			else if (point==0 || point==csName.Length-1)
				return null;  // Malformed expression
			else {
				string expr = csName.Substring(0, point);
				string memberName = csName.Substring(point+1, csName.Length-(point+1));
				object ob = ResolveCSName(expr);
				Type asType = ob as Type;

				try {
					if (ob==null)
						return null;
					else if (asType==null)
						// It's a regular object
						return ob.GetType().GetMember(memberName);
					else
						// It's a type name
						return asType.GetMember(memberName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
				} catch {
					return null;
				}
			}
		}

		string FormatMethodArgInfo(string expr, MethodInfo m) {
			ParameterInfo[] p = m.GetParameters();
			String[] strings = new String[2*p.Length+3];

			strings[0] = "[";
			strings[1] = expr;
			strings[2] = " ";
			for (int i=0; i<p.Length; i++) {
				strings[2*i+3] = p[i].Name;
				strings[2*i+4] = " ";
			}
			strings[strings.Length-1] = "]";
			return string.Concat(strings);
		}
		
		void UpdateVariableValue() {
			string variableName = code.CurrentDefinitionVariable;

			if (variableName != null) {
				object binding=code.LookupMemberExpression(variableName);
				if (binding != null)
					SetValueText(Meta.Writer.SafeWriteToString(binding, 100));
			}
		}

		void AproposClick(object sender, EventArgs e) {
			AproposForm f = AproposForm.theAproposForm;
			code.MaybeUnlockWindow();

			f.ShowDialog();
			if (f.DialogResult == DialogResult.OK)
				Meta.Apropos.ShowApropos(f.keyword.Text);
		}

		private void InterruptExecution_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.SingleStepMode = true;
		}

		static OpenFileDialog examplesDialog = new OpenFileDialog();
		private void examplesMenuItem_Click(object sender, System.EventArgs e) {
			examplesDialog.Filter = "Meta source code (*.meta)|*.meta";
			examplesDialog.InitialDirectory = Meta.Installation.installDirectory+new string(Path.DirectorySeparatorChar, 1)+"Examples";
			if (examplesDialog.ShowDialog()==DialogResult.OK)
				new Editor(examplesDialog.FileName).Show();
		}

		private void backgroundColorMenuItem_Click(object sender, System.EventArgs e) {
			colorDialog.AnyColor = true;
			colorDialog.Color = code.BackColor;
			if (colorDialog.ShowDialog()==DialogResult.OK)
				code.BackColor = colorDialog.Color;
		}

		private void forceGCMenuItem_Click(object sender, System.EventArgs e) {
			if (!Listener.IsRunning)
				EvalStack.CurrentThreadEvalStack.ClearForGC();
			System.GC.Collect();
			System.GC.WaitForPendingFinalizers();
		}

		private void loadMenuItem_Click(object sender, System.EventArgs e) {
			code.HandleLoadFile(sender, e);
		}

		private void pasteCommandMenuItem_Click(object sender, System.EventArgs e) {
			code.PastePreviousCommand();
		}

		private void menuItem8_Click(object sender, System.EventArgs e) {
			code.PasteNextCommand();
		}

		private void ApplyStyle(object sender, System.EventArgs e) {
			code.HandleStyle(sender, e);
		}

		private void EditStyles_Click(object sender, System.EventArgs e) {
			new StyleEditor(code).ShowDialog();
		}

		private void setDefaultMenuItem_Click(object sender, System.EventArgs e) {
			code.RecordDefaults();
		}

		private void contextMenu1_Popup(object sender, CancelEventArgs ea) {
			code.NoteUserSelection();
			bool running = (Listener.mainListener.evalThread != null && Listener.mainListener.evalThread.IsAlive);
			bool breakpointed = Meta.TopLevel.ThreadBeingDebugged!=null;

			string definitionName = code.CurrentDefinitionVariable;
			Meta.Procedure fbinding = this.Namespace.CheckFbinding(definitionName);

			contextExecute.Enabled = !running || breakpointed;
			contextSingleStep.Enabled = !running || breakpointed;
			contextBreakpoint.Enabled = fbinding!= null;
			contextBreakpoint.Checked = fbinding!=null && fbinding.Breakpointed;
			contextTrace.Enabled = fbinding!=null;
			contextTrace.Checked = fbinding!=null && fbinding.Traced;

			Expression exp = fbinding!=null?ExpressionAt(fbinding, code.UserSelection.start):null;
			contextBreakpointExpressionMenuItem.Enabled = exp!=null;
			contextBreakpointExpressionMenuItem.Checked = exp!=null && exp.executionMode.Breakpoint;
			traceAnalysisMenuItem.Enabled = exp!=null;
			traceAnalysisMenuItem.Checked = exp!=null && exp.traceAnalysis;
			contextContinueExecutionMenuItem.Enabled = contextBreakpointExpressionMenuItem.Enabled && breakpointed;
			

			Expression e = Expression.FindableExpression(code.CurrentVariableExpression);
			contextFindDefinition.Enabled = e!=null;
			contextFindDefinition.Text = (e==null)?"Find &Definition":("Find &Definition of "+e.definedIn);
			contextFindUsesMenuItem.Enabled = e!=null;
			contextFindUsesMenuItem.Text = (e==null)?"Find &uses":("Find &uses of "+e.definedIn);

			code.RestoreUserSelection();
			code.UnlockWindowDammit();
		}

		private void findMenuItem_Click(object sender, System.EventArgs e) {
			FindDialog f = new FindDialog(code);
			f.Show();
		}

		private void tailRecursionMenu_Popup(object sender, System.EventArgs e) {
			object opt = Expression.OptimizeTailCalls.DefaultValue;

			fullTailRecursionMenuItem.Checked = opt==Symbol.sAll;
			selfTailRecursionMenuItem.Checked = opt==Symbol.sSelf;
			noTailRecursionMenuItem.Checked = !selfTailRecursionMenuItem.Checked && !fullTailRecursionMenuItem.Checked;
		}

		private void fullTailRecursionMenuItem_Click(object sender, System.EventArgs e) {
			Expression.OptimizeTailCalls.DefaultValue = Symbol.sAll;
		}

		private void selfTailRecursionMenuItem_Click(object sender, System.EventArgs e) {
			Expression.OptimizeTailCalls.DefaultValue = Symbol.sSelf;
		}

		private void noTailRecursionMenuItem_Click(object sender, System.EventArgs e) {
			Expression.OptimizeTailCalls.DefaultValue = false;
		}

		private void ReindentMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			code.MarkUndo();
			code.LockWindow();
			Formatter.FormatExpression(code, code.TopLevelExpressionRegion(code.UserSelection.start).Start, false, false, true);
			code.RestoreUserSelection();
			code.UnlockWindow();
		}

		public void ReindentAllMenuItem_Click(object sender, System.EventArgs e) {
			ReindentAll();
		}

		public void ReindentAll() {
			code.LockWindow();
			code.NoteUserSelection();
			Formatter.FormatBuffer(code, false, false);
			code.RestoreUserSelection();
			code.UnlockWindow();
		}

		private void restyleMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			code.MarkUndo();
			code.LockWindow();
			Formatter.FormatExpression(code, code.TopLevelExpressionRegion(code.UserSelection.start).Start, true, true, true);
			code.RestoreUserSelection();
			code.UnlockWindow();
		}

		private void restyleAllMenuItem_Click(object sender, System.EventArgs e) {
			RestyleAll();
		}

		public void RestyleAll() {
			code.NoteUserSelection();
			code.MarkUndo();
			code.LockWindow();
			Formatter.FormatBuffer(code, true, true);
			code.RestoreUserSelection();
			code.UnlockWindow();
		}

		private void restyleAllPreservingCommentsMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			code.MarkUndo();
			code.LockWindow();
			Formatter.FormatBuffer(code, true, false);
			code.RestoreUserSelection();
			code.UnlockWindow();
		}

		private void clearAllBreakpointsMenuItem_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.ClearAllBreakpoints();
		}

		private void clearAllTracesMenuItem_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.ClearAllTraces();
		}

		private void breakpointExpressionMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			string definitionName = code.CurrentDefinitionVariable;
			Meta.Procedure fbinding = this.Namespace.CheckFbinding(definitionName);

			Expression exp = ExpressionAt(fbinding, code.UserSelection.start);
			if (exp!=null)
				Meta.TopLevel.ToggleBreakpoint(exp);
			code.RestoreUserSelection();
		}

		private void continueExecutionMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			string definitionName = code.CurrentDefinitionVariable;
			Meta.Procedure fbinding = this.Namespace.CheckFbinding(definitionName);

			Expression exp = ExpressionAt(fbinding, code.UserSelection.start);
			if (exp!=null)
				Meta.TopLevel.ThreadBeingDebugged.ContinueUntil(exp);
			code.RestoreUserSelection();
			CodeBox.SuppressKeyUp(Keys.C);
		}

		private void beginnerModeMenuItem_Click(object sender, System.EventArgs e) {
			Expression.OptimizeTailCalls.DefaultValue = false;
			Inspector.showDetail = false;
			EvalStack.showAllExpressions=true;
			Meta.TopLevel.AlwaysOpen2D = true;
		}

		private void windowsMenu_Select(object sender, System.EventArgs e) {
			ArrayList items = new ArrayList();

			for (int j=windowsMenu.DropDownItems.Count-1; j>=2; j--)
				windowsMenu.DropDownItems.RemoveAt(j);
			foreach (DictionaryEntry d in editorTable) {
				if (d.Value!=null) {
					Editor ed = (Editor)(d.Value);
					items.Add(new ToolStripMenuItem(ed.Text, null, new EventHandler(ed.WindowSelectHandler)));
				}
			}
			items.Sort(MenuComparer.Comparer);
			foreach (ToolStripMenuItem i in items)
				windowsMenu.DropDownItems.Add(i);
			windowsMenu.DropDownItems[2].Text = "&"+windowsMenu.DropDownItems[2].Text;
			for (int j = 3; j<windowsMenu.DropDownItems.Count && j<=13; j++)
				windowsMenu.DropDownItems[j].Text = "&"+(j-2).ToString()+"  "+windowsMenu.DropDownItems[j].Text;
		}
		private void WindowSelectHandler(object sender, EventArgs e) {
			BringToFront();
			if (WindowState==FormWindowState.Minimized)
				WindowState=FormWindowState.Normal;
		}

		private void traceLoadMenuItem_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.TraceLoading = !Meta.TopLevel.TraceLoading;
		}

		public float ZoomFactor {
			get {
				return code.ZoomFactor;
			}
			set {
				code.ZoomFactor = value;
			}
		}

		private void zoomMenu_Popup(object sender, System.EventArgs e) {
			zoom300.Checked = zoom200.Checked = zoom150.Checked = zoom120.Checked = zoom110.Checked
				= zoom100.Checked = zoom90.Checked = zoom80.Checked = false;
			
			if (ZoomFactor==3.0F)
				zoom300.Checked = true;
			else if (ZoomFactor==2.0F)
				zoom200.Checked = true;
			else if (ZoomFactor==1.5F)
				zoom150.Checked = true;
			else if (ZoomFactor==1.2F)
				zoom120.Checked = true;
			else if (ZoomFactor==1.1F)
				zoom110.Checked = true;
			else if (ZoomFactor==1.0F)
				zoom100.Checked = true;
			else if (ZoomFactor==0.9F)
				zoom90.Checked = true;
			else if (ZoomFactor==0.8F)
				zoom80.Checked = true;
		}

		private void zoom100_Click(object sender, System.EventArgs e) {
			ZoomFactor = 1.0F;
		}

		private void zoom90_Click(object sender, System.EventArgs e) {
			ZoomFactor = 0.9F;
		}

		private void zoom80_Click(object sender, System.EventArgs e) {
			ZoomFactor = 0.8F;
		}

		private void zoom110_Click(object sender, System.EventArgs e) {
			ZoomFactor = 1.1F;
		}

		private void zoom120_Click(object sender, System.EventArgs e) {
			ZoomFactor = 1.2F;
		}

		private void zoom150_Click(object sender, System.EventArgs e) {
			ZoomFactor = 1.5F;
		}

		private void zoom200_Click(object sender, System.EventArgs e) {
			ZoomFactor = 2.0F;
		}

		private void zoom300_Click(object sender, System.EventArgs e) {
			ZoomFactor = 3.0F;
		}

		private void ShowReferences_Click(object sender, System.EventArgs e) {
			code.HandleShowReferences(true);
		}

		private void ShowReferences2_Click(object sender, System.EventArgs e) {
			code.HandleShowReferences(false);
		}

		private void ISearchMenuItem_Click(object sender, System.EventArgs e) {
			if (code.iSearchMode)
				code.ISearchNext();
			else
				code.StartISearch();
		}

		private void FKeyMenuItem_Popup(object sender, System.EventArgs e) {
			bool gotOne = false;
			object titleob = Namespace.CheckBinding("menu-title");
			string title = (titleob!=null)?(titleob as string):null;
			foreach (FKeyMenuItem i in fKeyMenuItem.DropDownItems) {
				i.Update(this);
				gotOne |= i.Enabled;
			}
			fKeyMenuItem.Visible = fKeyMenuItem.Enabled = gotOne;
			if (title!=null)
				fKeyMenuItem.Text = title;
		}

		private void ReplaceMenuItem_Click(object sender, System.EventArgs e) {
			ReplaceDialog f = new ReplaceDialog(code);
			f.Show();
			//f.Dispose();
		}

		private void RemoveWhitespaceMenuItem_Click(object sender, System.EventArgs e) {
			RemoveWhitespace();
		}

		public void RemoveWhitespace() {
			code.LockWindow();
			code.RemoveLeadingWhitespace();
			SetArglistText("Reindenting and restyling ...");
			Formatter.FormatBuffer(code, true, false);
			code.UnlockWindow();
			SetArglistText("Done");
			ShowNamespace();
		}

		private void CheckMenuItem_Click(object sender, System.EventArgs e) {
			Listener.mainListener.EvalString("[Packages.Analysis.check-namespace]", false, false, fileToken, 0, false);
		}

		static void UpdateAllCheckMenus(Namespace n) {
			foreach (DictionaryEntry d in editorTable) {
				Editor e = d.Value as Editor;
				if (e!=null && e.Namespace==n)
					e.UpdateCheckMenuStatus();
			}
		}

		void UpdateCheckMenuStatus() {
			if (Namespace.HasWarnings) {
				int warnings=0;
				foreach (DictionaryEntry e in Namespace.Warnings) {
					ArrayList expressions = (ArrayList)e.Value;
					warnings += expressions.Count;
				}
				CheckMenu.Text = string.Format("&Check ({0})", warnings);
			} else
				CheckMenu.Text = "&Check";
		}

		private void CheckMenu_Popup(object sender, System.EventArgs ignore) {
			int warning;
			// Find first WarningMenu
			for (warning=0; warning<CheckMenu.DropDownItems.Count && !(CheckMenu.DropDownItems[warning] is WarningMenu); warning++);
			// Remove everything after it
			for (int i=CheckMenu.DropDownItems.Count-1; i>=warning; i--)
				CheckMenu.DropDownItems.RemoveAt(i);
			// Repopulate it.
			if (Namespace.Warnings!=null) {
				try {
					ArrayList headings = new ArrayList();
					foreach (DictionaryEntry e in this.Namespace.Warnings)
						headings.Add(e.Key);
					headings.Sort();
					foreach (string heading in headings) {
						IList exps = (IList)(Namespace.Warnings[heading]);
						if (exps.Count>0)
							CheckMenu.DropDownItems.Add(new WarningMenu(heading, exps));
					}
				} catch {}
			}
			AutoCheckMenuItem.Checked = Meta.TopLevel.AutoCheck;
		}

		private void AutoCheckMenuItem_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.AutoCheck = !Meta.TopLevel.AutoCheck;
		}

        bool regenerateGotoMenu = true;
		private void GotoMenuItem_Pop(object sender, System.EventArgs e) {
            if (!regenerateGotoMenu)
                return;
			ArrayList items = new ArrayList();
			code.LockWindow();
			CodeBox.ScrollPoint scroll = code.ScrollPosition;
			code.NoteUserSelection();
			CodeScanner s = code.ScanCharsFrom(0);
			while (!s.AtEndOfBuffer) {
				if ((s.LookingAt("[define") || s.LookingAt("(define"))
					&& code.RegionIndent(new Region(s.charIndex,0))==0) {
					string line = code.Lines[s.lineNumber];
					string title = line;
					int space = line.IndexOf(' ');
					if (space>=0)
						title = line.Substring(space+1, line.Length-(space+1));
					items.Add(new ToolStripMenuItem(title, null, new EventHandler(new GotoHandler(code, s.charIndex).Click)));
				}
				s.SkipForwardToBOL();
			}
			items.Sort(MenuComparer.Comparer);
			//foreach (MenuItem i in items)
			//	GotoMenuItem.DropDownItems.Add(i);
            ToolStripMenuItem[] i = new ToolStripMenuItem[items.Count];
            items.CopyTo(i);
            GotoMenuItem.DropDownItems.Clear();
            GotoMenuItem.DropDownItems.AddRange(i);
			code.RestoreUserSelection();
			code.ScrollPosition = scroll;
			code.UnlockWindowDammit();
            regenerateGotoMenu = false;
		}

		private void RecenterMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			code.ScrollToCenter();
		}

		private void contextFindUsesMenuItem_Click(object sender, System.EventArgs e) {
			code.HandleShowReferences(false);
		}

		private void traceAnalysisMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			Expression exp = ExpressionAtIncludingVariable(code.UserSelection.start);
			if (exp!=null) {
				if (exp is GlobalVariableReference)
					exp = ((GlobalVariableReference)exp).variable;
				exp.traceAnalysis = !exp.traceAnalysis;
			}
		}

		private class GotoHandler {
			int index;
			CodeBox code;
			public GotoHandler(CodeBox code, int index) {
				this.code = code;
				this.index = index;
			}

			public void Click(object sender, EventArgs e) {
				code.UserSelection = new Region(index, 0);
				code.RestoreUserSelection();
				code.ScrollToTop();
			}
		}

		private class MenuComparer : IComparer {
			public static MenuComparer Comparer = new MenuComparer();

			#region IComparer Members

			public int Compare(object x, object y) {
				string xt = ((ToolStripMenuItem)x).Text;
				string yt = ((ToolStripMenuItem)y).Text;

				if (xt==Listener.ListenerTitle && yt==Listener.ListenerTitle)
					return 0;
				else if (xt==Listener.ListenerTitle)
					return -1;
				else if (yt==Listener.ListenerTitle)
					return 1;
				else
					return String.Compare(xt, yt);
			}

			#endregion

		}

		public class CodeFileMenuItem : ToolStripMenuItem {
			public CodeFileMenuItem(string name, string fileName) {
				this.Text = name;
				this.fileName = fileName;
				Click += new EventHandler(ShowFile);
			}
			public CodeFileMenuItem(string name, string fileName, Keys shortcut) {
				this.Text = name;
				this.fileName = fileName;
				Click += new EventHandler(ShowFile);
				this.ShortcutKeys = shortcut;
			}
			string fileName;

			public void ShowFile(object sender, EventArgs e) {
				new Editor(fileName).Show();
			}
		}

		public class FKeyMenuItem : ToolStripMenuItem {
			public FKeyMenuItem(Keys key) {
				this.ShortcutKeys = key;
			}
			protected override void OnClick(EventArgs e) {
				Listener.mainListener.EvalString("["+ShortcutKeys.ToString()+"]", false, false,
                    ((Editor)((ToolStrip)GetCurrentParent()).FindForm()).fileToken, 0, true);
			}

			public void Update(Editor e) {
				Meta.Procedure p = e.Namespace.CheckFbinding(ShortcutKeys.ToString());
				if (p!= null) {
					Visible = Enabled = true;
					Text = (((IDocumentable)p).Documentation==null)?"Run procedure named"
                        :((IDocumentable)p).Documentation;
				} else {
					Visible = Enabled = false;
				}
			}
		}
	}
}
